<?php
namespace Api\Controller;

class ApiController extends  BaseController {

	protected $uid;
	protected $user;
	protected $system;
	protected $noCheck = array('login', 
					'reg', 
					'index', 
					'randstring', 
					'verifyphone', 
					'getcode', 
					'forget', 
					'up_img', 
					'about', 
					'introduce', 
					'del_addr', 
					'addrone', 
					'tie_model', 
					'news_model', 
					'news_list', 
					'news_info', 
					'model_index', 
					'shop_index', 
					'dealeryz', 
					'index_img', 
					'index_img_detail',
					'v_login', 
					'bangdin', 
					'shop_listtop', 
					'tie_list', 
					'two_category', 
					'keywode_shop', 
					'shop_index', 
					'shop_info', 
					'tie_info', 
					'shop_list', 
					'version', 
					'pro_list', 
					'pro_info', 
					'headline', 
					'live_list', 
					'maintainer_list', 
					'maintainer_info',
					'maintainer_comment',
					'home_brand',
					'brand_page',
					'brand_detail',
					'free_play_mj',
					'home_nearby_shop',
					'nearby_shop_detail',
					'nearby_shop_goods',
					'home_ad',
					'app_css',
					'sign_in_prizes', // 签到商品
					'prizes_detail',// 获取商品详情
					'img_verify',// 图像验证码
					'getcodenew',
					'jc_center',
					'maintainer_category',
					'app_open_ad',
					'getwechatparm',
					'wechat_js_config',
					'get_slider',
					'get_member_no',
					'mn_past_gj',//会员号往期冠军
					'home_goods',// 首页商品
					'home_goods_filter',// 首页商品筛选条件
					'product_discount',// 产品折扣
					'withdrawals_config',//提现配置
					'prizes_share_info',//签到成功后分享出去的页面浏览数据接口
					'home_img',//首页图片
					'uploadimgs',//上传组图接口
					'download_no',//下载娱管家号
					'icon',//图标接口
					'home_icon',//首页图标和文字
					'login_code',//登录页面代码
					'point_address',//获取经纬位置信息
					'getparm',
				);

	function _initialize() {
		parent::_initialize();
		$token = I('token');
		/*
		$where['token'] = I('token');
		$user = M('token')->where($where)->find();
		if (empty($user) && !in_array(ACTION_NAME, $this->noCheck)) {
			_A(false, 'Token does not exist,Please login');
		}
		$this->uid = $user['uid'];*/
		// 其它设备下线
		if($token){
			$user = M('user')->where(['cid'=>$token])->find();
			if(empty($user)){
				$user = M('token')->where(['token'=>$token])->find();
				if($user){
					$user['id'] = $user['uid'];
				}
			}
		}
		if($this->noCheck!='*'){
			if (empty($user) && !in_array(ACTION_NAME, $this->noCheck)) {
				_A(false, 'Token does not exist,Please login');
			}
		}
		if(!empty($user)){
			$this->uid = $user['id'];
		}
		if($this->uid){
			$this->user = M('user')->where(['id'=>$this->uid])->find();
		}
		if(!empty($this->user)){
			if(!$this->user['status']){
				_A(false, 'Token does not exist,Please login');
			}
		}
		$this->system = I('system');
	}

	function index() {
		$res = M('Api')->order('id desc')->select();

		$this->assign('list', $res);
		$this->display();
	}

	// 获取随机位数数字

	protected function randString($len = 4) {
		$chars = str_repeat('0123456789', $len);
		$chars = str_shuffle($chars);
		$str = substr($chars, 0, $len);
		return $str;
	}

	/* *
	 * Dragon
	 * 2016-11-26
	 * 验证手机号是否注册过
	 * */

	public function verifyphone() {
		$where['phone'] = trim(I('phone'));
		$res = M('User')->where($where)->select();
		if ($res) {
			$this->ajaxReturn(array('s' => false, 'm' => "该号码已经注册过,不能重复注册!"));
		} else {
			$this->ajaxReturn(array('s' => true, 'm' => "新用户"));
		}

	}

	//验证经销商电话
	public function dealeryz() {
		$phone = I('phone');
		$res = M('dealer')->where(array('phone' => $phone))->find();
		if ($res) {
			$this->ajaxReturn(array('s' => true, 'd' => $res['id']));
		} else {
			$this->ajaxReturn(array('s' => false));
		}

	}

	//发送短信
	public function getCode() {
		$phone = trim(I('phone'));

		$num = $this->randString();
			$this->ajaxReturn(array('s' => false, 'm' => "发送失败"));
		if (preg_match("/^1[0123456789]{1}\d{9}$/", $phone)) {

			Vendor('Alidayu.top.TopClient');
			$c = new \TopClient;

			$c->appkey = C('AlidayuAppKey');
			$c->secretKey = C('AlidayuAppSecret');
			Vendor('Alidayu.top.request.AlibabaAliqinFcSmsNumSendRequest');
			$req = new \AlibabaAliqinFcSmsNumSendRequest;

			// 短信类型，传入值请填写normal
			$req->setSmsType("normal");

			//【阿里大鱼】欢迎使用阿里大鱼服务。
			$req->setSmsFreeSignName("注册验证");
			$req->setSmsParam("{\"code\":\"$num\",\"name\":\"娱助理\"}");
			//短信接收号码
			$req->setRecNum($phone);
			//短信模板ID，传入的模板必须是在阿里大鱼“管理中心-短信模板管理”中的可用模板。示例：SMS_585014
			$req->setSmsTemplateCode("SMS_33900274");
			$resp = $c->execute($req);
			$data = array('phone' => $phone, 'code' => $num, 'ctime' => time());
			//缓存code phone
			$flag = M('varify')->where('phone=' . $phone)->find();
			if ($flag) {
				$varifyInfo = M('varify')->where('phone=' . $phone)->data($data)->save();
			} else {
				$varifyInfo = M('varify')->data($data)->add();
			}

			$this->ajaxReturn(array('s' => true, 'm' => "发送成功"));

		} else { 
			$this->ajaxReturn(array('s' => false, 'm' => "发送失败"));
		}

	}


	public function getCodeNew()
	{
		$phone = trim(I('phone'));
		$img_code = trim(I('img_code'));
		$vid = trim(I('vid', 1));
		if(empty($img_code)){
			$this->ajaxReturn(array('s'=>false, 'm'=>"请输入图像验证码"));
		}
		if(!$this->check_verify($img_code, $vid)){
			$this->ajaxReturn(array('s'=>false, 'm'=>"图形验证码不正确"));
		}
		
		$num = $this->randString();
		if (preg_match("/^1[0123456789]{1}\d{9}$/", $phone)) {

			Vendor('Alidayu.top.TopClient');
			$c = new \TopClient;

			$c->appkey = C('AlidayuAppKey');
			$c->secretKey = C('AlidayuAppSecret');
			Vendor('Alidayu.top.request.AlibabaAliqinFcSmsNumSendRequest');
			$req = new \AlibabaAliqinFcSmsNumSendRequest;

			// 短信类型，传入值请填写normal
			$req->setSmsType("normal");

			//【阿里大鱼】欢迎使用阿里大鱼服务。
			$req->setSmsFreeSignName("注册验证");
			$req->setSmsParam("{\"code\":\"$num\",\"name\":\"娱管家\"}");
			//短信接收号码
			$req->setRecNum($phone);
			//短信模板ID，传入的模板必须是在阿里大鱼“管理中心-短信模板管理”中的可用模板。示例：SMS_585014
			$req->setSmsTemplateCode("SMS_33900274");
			try{
				$resp = $c->execute($req);
				if(!empty($resp->result->msg) && $resp->result->msg == 'OK'){
					$data = array('phone' => $phone, 'code' => $num, 'ctime' => time());
					//缓存code phone
					$flag = M('varify')->where('phone=' . $phone)->find();
					if ($flag) {
						$varifyInfo = M('varify')->where('phone=' . $phone)->data($data)->save();
					} else {
						$varifyInfo = M('varify')->data($data)->add();
					}
					$this->ajaxReturn(array('s' => true, 'm' => "发送成功"));
				}else{
					$this->ajaxReturn(array('s' => false, 'm' => "发送失败"));
				}
			}catch (\Exception $e){
				$this->ajaxReturn(array('s' => false, 'm' => $e->msg));
			}
		} else {
			$this->ajaxReturn(array('s' => false, 'm' => "发送失败"));
		}		
	}


 	/**
     * 检测验证码
     * @param  integer $id 验证码ID
     * @return boolean 检测结果
     */
    private function check_verify($code, $vid = 1)
    {
        $verify = new \Think\ApiVerify(['reset' => false]);
        return $verify->check($code, $vid);
    }	

	/* *
	 * Dragon
	 * 2016-11-28
	 * 注册
	 * */

	public function reg() {
		$phone = I('phone');
		$code = trim(I('code'));
		$password = I('pwd');
		$parent_no = I('parent_no');
		$parent_no = trim($parent_no);

		$img = C('SiteUrl') . 'Public/upload/userimg/t.jpg';
		if (empty($phone) || empty($code) || empty($password)) {
			$this->ajaxReturn(array('s' => false, 'm' => '请输入完整信息'));
		}

		$phoneInfo = M('user')->where('phone="' . $phone . '"')->find();
		if(!empty($phoneInfo)){
			$this->ajaxReturn(array('s' => false, 'm' => '手机号已存在'));
		}

		$varifyInfo = M('varify')->where('phone=' . $phone)->find();

		$data = array('nickname' => "用户" . $phone, 'phone' => $phone, 'pwd' => md5($password), 'ctime' => time(), 'img' => $img);

		if (time() > $varifyInfo['ctime'] + 1800) {
			$this->ajaxReturn(array('s' => false, 'm' => '验证码失效!'));
		}

		if ($phone == $varifyInfo['phone'] && $code == $varifyInfo['code']) {
			$res_add = user_reg($data, $parent_no);
			if(!$res_add){
				$this->ajaxReturn(array('s' => false, 'm' => '注册失败!'));
			}
			$token = md5($res_add);
			if ($res_add) {
				$this->ajaxReturn(array('s' => true, 'm' => '注册成功!', 'd' => md5($res_add)));
			} else {
				$this->ajaxReturn(array('s' => false, 'm' => '注册失败!'));
			}
		} else {
			$this->ajaxReturn(array('s' => false, "m" => "手机号或验证码错误!"));
		}

	}
	/* *
	 * Dragon
	 * 2011-1-7
	 * 绑定2
	 * */

	public function bangdintow() {
		$userdata=I('post.');
	 	
		$uid=$this->uid;
		$nickname=$userdata['data']['nickname'];
		$openid=$userdata['data']['openid'];
		if($userdata['data']['id']=="qq"){
			$qqunionid = '';
			$obj = !empty($userdata['data']['obj']) ? json_decode(htmlspecialchars_decode($userdata['data']['obj']), true) : [];
			if($obj && !empty($obj['authResult']['access_token'])){
				$unionidRes = file_get_contents("https://graph.qq.com/oauth2.0/me?access_token={$obj['authResult']['access_token']}&unionid=1");
				if (strpos($unionidRes, 'callback') !== false) {
		            $lpos = strpos($unionidRes, '(');
		            $rpos = strrpos($unionidRes, ')');
		            $unionidRes = substr($unionidRes, $lpos + 1, $rpos - $lpos - 1);
		        }
		        $unionidRes = json_decode($unionidRes, true);
		        if($unionidRes && !empty($unionidRes['unionid'])){
		        	$qqunionid = $unionidRes['unionid'];
		        }
			}

			$data = array(
			'qqnickname' => $nickname,
			'qqopenid'	 => $openid,
			'qqunionid'	 => $qqunionid,
			);
		}else{
			$unionid=$userdata['data']['unionid'];
			$data = array(
			'wxnickname' =>$nickname, 
			'wxopenid'=>$openid,
			'unionid'=>$unionid,
			);
		}
		try {
			$model = M('user');
			$res=$model->where(array('id'=>$uid))->data($data)->save();
		//$a= M()->_sql();
		} catch(\Exception $e) {
			$this->ajaxReturn(array('s' => false, 'm' => '参数错误sql'));
		}
		$this->ajaxReturn(array('s' => true, 'm' => '绑定成功!'));
	}
	/* *
	 * Dragon
	 * 2011-1-7
	 * 绑定
	 * */

	public function bangdin() {
		$phone = I('phone');
		$code = trim(I('code'));
		$password = I('pwd');
		$userdata=I('data');
		$parent_no = I('parent_no');
		$parent_no = trim($parent_no);

		$userdata = json_decode($userdata, true);
		$nickname=$userdata['userInfo']['nickname'];
		$openid=$userdata['authResult']['openid'];
		if($userdata['id']=="qq"){
			if($userdata['userInfo']['gender']=="男"){
				$sex=1;
			}else{
				$sex=2;
			}
			$img=$userdata['userInfo']['figureurl_qq_1'];
			$data = array(
			'qqnickname' =>$nickname,
		    'phone' => $phone, 
		    'pwd' => md5($password), 
		    'ctime' =>time(), 
		    'img' => $img,
			'sex'=>$sex,
			'qqopenid'=>$openid,
			);
			$data2 = array(
			'qqnickname' =>$nickname,
		    'pwd' => md5($password), 
		    'img' => $img,
			'sex'=>$sex,
			'qqopenid'=>$openid,
			);
			
		}else{
			$sex=$userdata['userInfo']['sex'];
			$img=$userdata['userInfo']['headimgurl'];
			$unionid=$userdata['userInfo']['unionid'];
			$data = array(
			'wxnickname' =>$nickname, 
			'phone' => $phone, 
			'pwd' => md5($password), 
			'ctime' =>time(), 
			'img' => $img,
			'sex'=>$sex,
			'wxopenid'=>$openid,
			'unionid'=>$unionid,
			);
			
			$data2=array(
			'wxnickname' =>$nickname, 
			'pwd' => md5($password), 
			'img' => $img,
			'sex'=>$sex,
			'wxopenid'=>$openid,
			'unionid'=>$unionid,
			);
		}

		$phoneInfo = M('user')->where(array('phone'=>$phone))->find();
		if(empty($phoneInfo)){
			$varifyInfo = M('varify')->where('phone=' . $phone)->find();
			if (time() > $varifyInfo['ctime'] + 1800) {
				$this->ajaxReturn(array('s' => false, 'm' => '验证码失效!'));
			}
			if ($phone == $varifyInfo['phone'] && $code == $varifyInfo['code']) {
				$res_add = user_reg($data, $parent_no);
				if(!$res_add){
					$this->ajaxReturn(array('s' => false, 'm' => '注册失败!'));
				}
				$token = md5($res_add);
				if ($res_add) {
					$this->ajaxReturn(array('s' => true, 'm' => '绑定成功!', 'd' => md5($res_add)));
				} else {
					$this->ajaxReturn(array('s' => false, 'm' => '绑定失败1!'));
				}
			} else {
				$this->ajaxReturn(array('s' => false, "m" => "手机号或验证码错误!"));
			}
		}else{
			try {
			$obj=M('user')->where(array('id'=>$phoneInfo['id']))->data($data2)->save();
			} catch(Exception $e) {
				$this->ajaxReturn(array('s' => false, 'm' => '参数错误sql'));
			}
			$token=M('token')->where(array('uid'=>$phoneInfo['id']))->find();
			$this->ajaxReturn(array('s' => true, 'm' => '绑定成功!', 'd' =>$token['token']));
		}
	}

	/* *
	 * Dragon
	 * 2016-11-28
	 * 登入
	 * */

	public function login() {
		$phone 		= I('phone');
		$password 	= I('pwd');
		$cid 		= I('cid');
		$clientid 	= I('clientid');
		$eqsb 		= I('eqsb');
		$wxmopenid  = I('wxmopenid');
		if(empty($phone)){
			$this->ajaxReturn(array('s' => false, 'm' => "请输入手机号"));
		}
		$where = array('phone' => $phone, 'pwd' => md5($password));
		$user = M('user')->where($where)->find();
		if ($user) {
			$update_data = array(
				'eqsb'		=> $eqsb,
			);
			if($eqsb != 'web'){// 非web登录
				$update_data['cid'] = $cid;
			}

			if($clientid){// 个推id
				$update_data['clientid'] = $clientid;
				M('user')->where(['clientid'=>$clientid])->save(array('clientid'=>''));	
			}
			if($wxmopenid){// 微信服务号openid
				$update_data['wxmopenid'] = $wxmopenid;
				M('user')->where(['wxmopenid'=>$wxmopenid])->save(['wxmopenid'=>'']);
			}
			$res_save = M('user')->where($where)->save($update_data);
			$hasToken = M('token')->where('uid="' . $user['id'] . '"')->find();
			$token = array('uid' => $user['id'], "token" => md5($user['id']));
			if ($hasToken) {
				M('token')->save($token);
			} else {
				M('token')->add($token);
			}
			$token = md5($user['id']);
			M('user')->where(['id'=>$user['id']])->setInc('login_num', 1);
			if($eqsb == 'web'){
				$cid = $token;
			}
			$this->ajaxReturn(array('s' => true, 'd' => $cid, 't'=>$token));
		} else {
			$this->ajaxReturn(array('s' => false, 'm' => "账号密码错误"));
		}
	}

	/* *
	 * Dragon
	 * 2016-11-28
	 * 找回密码
	 * */

	public function forget() {
		$phone = I('phone');
		$code = I('code');
		$pwd = I('pwd');

		if (empty($phone) || empty($code) || empty($pwd)) {
			$this->ajaxReturn(array('s' => false, 'm' => '每一项都不能为空'));
		}

		$varifyInfo = M('varify')->where('phone=' . $phone)->find();

		if (time() > $varifyInfo['ctime'] + 1800) {
			$this->ajaxReturn(array('s' => false, 'm' => '验证码失效'));
		}

		if ($phone != $varifyInfo['phone'] || $code != $varifyInfo['code']) {
			$this->ajaxReturn(array('s' => false, 'm' => "手机号或验证码错误!"));
		}

		$where['phone'] = $phone;
		$data = array('pwd' => md5($pwd));

		if(empty(M('user')->where($where)->find())){
			$this->ajaxReturn(array('s' => false, 'm' => '不存在该手机号用户'));
		}
		
		try {
			$list = M('user')->where($where)->save($data);
			
		} catch(Exception $e) {
			$this->ajaxReturn(array('s' => false, 'm' => '参数错误sql'));
		}
	
		$this->ajaxReturn(array('s' => true, 'm' => "修改成功"));
		

	}

	/* *
	 * Dragon
	 * 2016-11-28
	 * 获取用户信息
	 * */

	public function userinfo() {
		$uid = $this->uid;
		//$uid	=2;
		$list = M('user')->where('id="' . $uid . '"')->find();
		$res = M('shop')
        ->where(['uid|phone|tel'=>[$this->uid, $this->user['phone'], $this->user['phone'], '_multi'=>ture], 'status'=>1])
        ->find();
        if(empty($res)){
			$res = M('shop')
	        ->where(['uid|phone|tel'=>[$this->uid, $this->user['phone'], $this->user['phone'], '_multi'=>ture]])
	        ->find();
        }
		// $res = M('shop')->where('uid="' . $uid . '"')->find();
		// if(empty($res)){
		// 	$res = M('shop')->where(['phone'=>$this->user[ 'phone']])->find();
		// }
		// if(empty($res)){
		// 	$res = M('shop')->where(['tel'=>$this->user[ 'phone']])->find();
		// }
		if ($res) {
			$list['status'] = intval($res['status']);
		} else {
			$list['status'] = 'f';
		}

		$list['shop_id'] = $res['id'];
		$order_list = M('order')->where('uid="' . $uid . '"')->select();
		foreach ($order_list as $k => $v) {
			$ids = $v['status'];
			switch ($ids) {//0待付款1待发货2待收货3待评价
				case '0' :
					$where = array('uid' => $uid, 'status' => 0);
					$result_one = M('order')->where($where)->order('id desc')->select();
					break;
				case '1' :
					$where = array('uid' => $uid, 'status' => 1);
					$result_two = M('order')->where($where)->order('id desc')->select();
					break;
				case '2' :
					$where = array('uid' => $uid, 'status' => 2);
					$result_three = M('order')->where($where)->order('id desc')->select();
					break;
				case '3' :
					$where = array('uid' => $uid, 'status' => 3);
					$result_four = M('order')->where($where)->order('id desc')->select();
					break;
			}
		}
		if (!empty($result_one)) {
			$result_one = 0;
		} else {
			$result_one = 1;
		}
		if (!empty($result_two)) {
			$result_two = 0;
		} else {
			$result_two = 1;
		}
		if (!empty($result_three)) {
			$result_three = 0;
		} else {
			$result_three = 1;
		}
		if (!empty($result_four)) {
			$result_four = 0;
		} else {
			$result_four = 1;
		}
		$list['before'] = $result_one;
		$list['now'] = $result_two;
		$list['after'] = $result_three;
		$list['ping'] = $result_four;
		if ($list) {
			$this->ajaxReturn(array('s' => true, 'd' => $list));
		} else {
			$this->ajaxReturn(array('s' => false));
		}
	}

	/*
	 * 修改订单是否阅读的状态
	 * liuzm
	 * 2016年12月16日03:49:46*/
	public function up_readstatus() {
		$uid = $this->uid;
		$type = I('type');
		$order_list = M('order')->where('uid="' . $uid . '"')->select();
		$data = array('read_status' => 1);
		switch ($type) {//0待付款1待发货2待收货
			case '0' :
				$where = array('uid' => $uid, 'status' => 0);
				break;
			case '1' :
				$where = array('uid' => $uid, 'status' => 1);
				break;
			case '2' :
				$where = array('uid' => $uid, 'status' => 2);
				break;
			case '3' :
				$where = array('uid' => $uid, 'status' => 3);
				break;
		}
		try {
			$result = M('order')->where($where)->save($data);
		} catch(Exception $e) {
			$this->ajaxReturn(array('s' => false));
		}
		$this->ajaxReturn(array('s' => true));
	}

	/* *
	 * Dragon
	 * 2016-11-28
	 * 修改昵称
	 * */
	public function up_nickname() {
		$nickname = I('nickname');
		$data = array('nickname' => $nickname, );
		$list = M('user')->where('id="' . $this->uid . '"')->save($data);
		if ($list) {
			$this->ajaxReturn(array('s' => true, 'm' => "修改成功"));
		} else {
			$this->ajaxReturn(array('s' => false, 'm' => "修改失败"));
		}
	}

	/* *
	 * Dragon
	 * 2016-11-28
	 * 修改年龄
	 * */

	public function up_age() {
		$aeg = I('age');
		$data = array('age' => $aeg, );
		$list = M('user')->where('id="' . $this->uid . '"')->save($data);
		if ($list) {
			$this->ajaxReturn(array('s' => true, 'm' => "修改成功"));
		} else {
			$this->ajaxReturn(array('s' => false, 'm' => "修改失败"));
		}
	}

	/* *
	 * Dragon
	 * 2016-11-28
	 * 修改性别
	 * */

	public function up_sex() {
		$sex = I('sex');
		$data = array('sex' => $sex, );
		$list = M('user')->where('id="' . $this->uid . '"')->save($data);
		if ($list) {
			$this->ajaxReturn(array('s' => true, 'm' => "修改成功"));
		} else {
			$this->ajaxReturn(array('s' => false, 'm' => "修改失败"));
		}
	}

	/* *
	 * Dragon
	 * 2016-11-28
	 * 修改头像
	 * */

	public function up_haerimg() {
		$src = I('src');
		$data = array('img' => $src, );
		$list = M('user')->where('id="' . $this->uid . '"')->save($data);
		if ($list) {
			$this->ajaxReturn(array('s' => true, 'm' => "修改成功"));
		} else {
			$this->ajaxReturn(array('s' => false, 'm' => "修改失败"));
		}
	}

	/* *
	 * Dragon
	 * 2016-11-28
	 * 上传图片
	 * */

	public function up_img() {
		if (empty($_FILES) && empty($_POST['imgdata'])) {
			_A(false, 'plase upload image');
		}

		$npath = './'.C('UPLOAD_PATH').'/userimg/';
		$nfilename = date('Ymd_His') . '_' . mt_rand(1000, 9999);
		$d = $_POST;
		if(empty($_FILES)){
			$img = $_POST['imgdata'];
			$img = explode(',', $img);
			$exe =  str_replace('data:image/', '', $img[0]);  //data:image/png;base64
			$exe =  str_replace(';base64', '', $exe); 
		}else{
			$file = reset($_FILES);
			$exe = pathinfo($file['name'])['extension'];
		}
		$newName = $npath . $nfilename . '.'.$exe;
		
		
		if(empty($_FILES)){
			file_put_contents($newName, base64_decode($img[1]));
		}else{
			move_uploaded_file($file['tmp_name'], $newName);
			img_orientation_bug($newName);
		}
		$timage = date('Ymd_His') . '_' . mt_rand(1000, 9999);
		$timage = $npath . $nfilename . '.jpg';
		$this->cutImage($newName, $timage, 0, 0, $d['x'], $d['y'], $d['w'], $d['h'], 400, 400);
		//p($timage);
		_A(true, 'upload ok', C('SiteUrl') . $timage);

	}

	/* *
	 * Dragon
	 * 2016-11-28
	 * 裁切图片
	 * */

	public function cutImage($fimage, $timage, $x1, $y1, $x2, $y2, $w, $h, $dw, $dh) {
		$pinfo = pathinfo($fimage);
		$exe = $pinfo['extension'];
		$exe = strtolower($exe);
		
		if($exe == 'png'){
			$dst_im = imagecreatefrompng($fimage);
		}else{
			$dst_im = imagecreatefromjpeg($fimage);
		}
		
		//P($dst_im);
		$src_im = imagecreatetruecolor($dw, $dh);
		imagecopyresized($src_im, $dst_im, $x1, $y1, $x2, $y2, $dw, $dh, $w, $h);
		imagejpeg($src_im, $timage, 90);
		imagedestroy($dst_im);
		imagedestroy($src_im);

	}

	/* *
	 * Dragon
	 * 2016-11-28
	 * 修改个性签名
	 * */

	public function up_sig() {
		$sig = I('sig');
		$data = array('sig' => $sig, );
		$list = M('user')->where('id="' . $this->uid . '"')->save($data);
		if ($list) {
			$this->ajaxReturn(array('s' => true, 'm' => "修改成功"));
		} else {
			$this->ajaxReturn(array('s' => false, 'm' => "修改失败"));
		}
	}

	/* *
	 * Dragon
	 * 2016-11-28
	 * 修改密码
	 * */

	public function up_pwd() {
		$pwd = I('out_pwd');
		$newpwd = I('new_pwd');
		$outpwd = M('user')->where('id="' . $this->uid . '"')->find();
		if (md5($pwd) != $outpwd['pwd']) {
			$this->ajaxReturn(array('s' => false, 'm' => "原密码错误"));
		}
		$data = array('pwd' => md5($newpwd));
		$list = M('user')->where('id="' . $this->uid . '"')->save($data);
		if ($list) {
			$this->ajaxReturn(array('s' => true, 'm' => "修改成功"));
		} else {
			$this->ajaxReturn(array('s' => false, 'm' => "修改失败"));
		}
	}

	/* *
	 * Dragon
	 * 2016-11-28
	 * 关于我们
	 * */

	public function about() {
		$where['id'] = 1;
		$data = M('Article')->where($where)->find();
		$this->ajaxReturn(array('s' => true, 'd' => $data['content']));

	}

	/* *
	 * Dragon
	 * 2016-11-28
	 * 软件介绍
	 * */

	public function introduce() {
		$where['id'] = 2;
		$data = M('Article')->where($where)->find();
		$this->ajaxReturn(array('s' => true, 'd' => $data['content']));

	}

	/* *
	 * Dragon
	 * 2016-11-28
	 * 咨询客服
	 * */

	public function seme() {
		$content = I('content');
		$outpwd = M('user')->where('id="' . $this->uid . '"')->find();
		//p($outpwd);
		$data = array('phone' => $outpwd['phone'], 'content' => $content, 'ctime' => time());
		$res = M('Seme')->add($data);
		if ($res) {
			$this->ajaxReturn(array('s' => true, 'm' => "留言成功"));
		} else {
			$this->ajaxReturn(array('s' => false, 'm' => "留言失败"));
		}
	}

	/* *
	 * Dragon
	 * 2016-11-28
	 * 地址列表
	 * */

	public function addr() {
		$res = M('Addr')->where('uid="' . $this->uid . '"')->select();
		if ($res) {
			$this->ajaxReturn(array('s' => true, 'd' => $res));
		} else {
			$this->ajaxReturn(array('s' => false));
		}

	}

	/* *
	 * Dragon
	 * 2016-11-28
	 * 设为默认
	 * */

	public function def() {

		$id = I('id');
		try {
			$re = M('Addr')->where('uid="' . $this->uid . '"')->save(array('status' => 0));
			$res = M('Addr')->where('id="' . $id . '"')->save(array('status' => 1));
			if ($res) {
				$this->ajaxReturn(array('s' => true, 'm' => "成功"));
			} else {
				$this->ajaxReturn(array('s' => false, 'm' => "失败1"));
			}
		} catch(Exception $e) {
			$this->ajaxReturn(array('s' => false, 'm' => "失败2"));
		}
	}

	/* *
	 * Dragon
	 * 2016-11-28
	 * 添加地址
	 * */

	public function add_addr() {
		$c_name = I('c_name');
		$c_phome = I('c_phome');
		$city = I('city');
		$pro = I('pro');
		$area = I('area');
		$add = I('add');
		$status = I('status');
		$ecp = M('Addr')->where('uid="' . $this->uid . '"')->select();
		if (!$ecp) {
			$status = 1;
		}

		$data = array('uid' => $this->uid, 'c_name' => $c_name, 'c_phome' => $c_phome, 'city' => $city, 'pro' => $pro, 'area' => $area, 'add' => $add, 'status' => $status, );
		if ($status == 1) {
			$re = M('Addr')->where('uid="' . $this->uid . '"')->save(array('status' => 0));

		}

		$res = M('Addr')->add($data);

		if ($res) {
			$this->ajaxReturn(array('s' => true, 'm' => "添加成功"));
		} else {
			$this->ajaxReturn(array('s' => false, 'm' => "添加失败"));
		}

	}

	/* *
	 * Dragon
	 * 2016-11-28
	 * 删除地址
	 * */

	public function del_addr() {
		$id = I('id');
		$res = M('Addr')->where('id="' . $id . '"')->delete();
		if ($res) {
			$this->ajaxReturn(array('s' => true, 'm' => "删除成功"));
		} else {
			$this->ajaxReturn(array('s' => false, 'm' => "删除失败"));
		}

	}

	/* *
	 * Dragon
	 * 2016-11-28
	 * 获取单个地址
	 * */

	public function addrone() {
		$id = I('id');
		$res = M('Addr')->where('id="' . $id . '"')->find();
		if ($res) {
			$this->ajaxReturn(array('s' => true, 'd' => $res));
		} else {
			$this->ajaxReturn(array('s' => false));
		}

	}

	/* *
	 * Dragon
	 * 2016-11-28
	 * 修改地址
	 * */

	public function up_addr() {
		$where['id'] = I('id');
		$c_name = I('c_name');
		$c_phome = I('c_phome');
		$city = I('city');
		$pro = I('pro');
		$area = I('area');
		$add = I('add');
		$status = I('status');
		$data = array('c_name' => $c_name, 'c_phome' => $c_phome, 'city' => $city, 'pro' => $pro, 'area' => $area, 'add' => $add, 'status' => $status, );
		if ($status == 1) {
			$re = M('Addr')->where('uid="' . $this->uid . '"')->save(array('status' => 0));

		}
		$res = M('Addr')->where($where)->save($data);
		if ($res) {
			$this->ajaxReturn(array('s' => true, 'm' => "修改成功"));
		} else {
			$this->ajaxReturn(array('s' => false, 'm' => "修改失败"));
		}

	}

	public function apply_in_join_test() {  
		$showimg = $this->uploadimgsy('showimg'); 
		$data = array( 
			'showimg' => $showimg,  
		);
		P($data); 
	}
	/* *
	 * Dragon
	 * 2016-11-28
	 * 申请入驻
	 * */
	public function apply_in_join() {
		$nobase64 = I('nobase64');
		$shopname = I('shopname');
		$name = I('name');

		$ds = I('post.ds');
		$ds = str_replace("\n", "<br />", $ds);
		$pro = I('pro');
		$city = I('city');
		$area = I('area');
		$addr = I('addr');
		$tel = I('phone');
		$did = I('did');
		$card = I('card');
		if($nobase64){
			$boss_img = I('boss_img');
			$listimg = I('listimg');
			$showimg = I('showimg');
			$yyzz = I('yyzz');
		}else{
			$boss_img = $this->uploadimgsy('boss_img');
			$listimg = $this->uploadimgsy('listimg');
			$showimg = $this->uploadimgsy('showimg');
			$yyzz = $this->uploadimgsy('yyzz');
		}
		$uid = $this->uid;
		$lat = I('lat');
		//坐标
		$lng = I('lng');
		//坐标
		$rest=M('User')->where(array('id'=>$uid))->find();
		$phone=$rest['phone'];
		
		$wecat= M('shop')->where(array('phone'=>$phone))->find();
		if($wecat){
			$this->ajaxReturn(array('s' => false, 'm' => "重复提交"));
		}else{
			$data = array(
			'uid' => $uid,
			'name' => $name, 
			'shopname' => $shopname, 
			'ds' => $ds, 
			'pro' => $pro, 
			'city' => $city, 
			'area' => $area, 
			'addr' => $addr, 
			'tel' => $tel, 
			'did' => $did, 
			'card' => $card, 
			'listimg' => $listimg, 
			'boss_img' => $boss_img, 
			'showimg' => $showimg, 
			'renqi' => 0, 
			'yyzz' => $yyzz, 
			'lng' => $lng, 
			'lat' => $lat, 
			'ctime' => time(),
			'phone'=>$phone); 
		
			$res = M('shop')->data($data)->add();
			if ($res) {
				$this->ajaxReturn(array('s' => true, 'm' => "提交成功"));
			} else {
				$this->ajaxReturn(array('s' => false, 'm' => "提交失败"));
			}
		}
	}

	/* *
	 * Dragon
	 * 2016-11-28
	 * 获取自己的店铺
	 * */
	public function shop_updata_set() {
		$where['uid'] = $this->uid;

		$list = M('shop')->where($where)->find();

		$re = file_get_contents($list['listimg']);
		$list['listimg'] = 'data:image/png;base64,' . base64_encode($re);
		$list['showimg'] = explode(",", $list['showimg']);
		$list['yyzz'] = explode(",", $list['yyzz']);
		$list['boss_img'] = explode(",", $list['boss_img']);
		$list['ds'] = str_replace("<br />", "\n", $list['ds']);

		if ($list) {
			$this->ajaxReturn(array('s' => true, 'd' => $list));
		} else {
			$this->ajaxReturn(array('s' => false, 'm' => "获取失败"));
		}

	}

	/* *
	 * Dragon
	 * 2016-11-28
	 * 数组转base64
	 * */
	public function base64() {
		if (I('url') == "") {
			$this->ajaxReturn(array('s' => false, ));
		}
		$url = I('url');
		$re = file_get_contents($url);
		$retun = 'data:image/png;base64,' . base64_encode($re);
		$this->ajaxReturn(array('s' => true, 'd' => $retun));
	}

	/* *
	 * Dragon
	 * 2016-11-28
	 * 修改入驻信息
	 * */
	public function updata_shop() {
		$id = I('id');
		$shopname = I('shopname');
		$name = I('name');
		$ds = I('ds');
		$ds = str_replace("\n", "<br />", $ds);
		$pro = I('pro');
		$city = I('city');
		$area = I('area');
		$addr = I('addr');
		$phone = I('phone');
		$dphone = I('dphone');
		$card = I('card');
		$boss_img = $this->uploadimgsy('boss_img');
		$listimg = $this->uploadimgsy('listimg');
		$showimg = $this->uploadimgsy('showimg');
		$yyzz = $this->uploadimgsy('yyzz');
		$uid = $this->uid;
		$lat = I('lat');
		//坐标
		$lng = I('lng');
		//坐标
		$data = array('name' => $name, 'shopname' => $shopname, 'ds' => $ds, 'pro' => $pro, 'city' => $city, 'area' => $area, 'addr' => $addr, 'phone' => $phone, 'dphone' => $dphone, 'card' => $card, 'listimg' => $listimg, 'boss_img' => $boss_img, 'showimg' => $showimg, 'renqi' => 0, 'yyzz' => $yyzz, 'lng' => $lng, 'lat' => $lat, );

		$res = M('shop')->where(array('id' => $id))->save($data);
		if ($res) {
			$this->ajaxReturn(array('s' => true, 'm' => "提交成功"));
		} else {
			$this->ajaxReturn(array('s' => false, 'm' => "提交失败"));
		}

	}

	/* *
	 * Dragon
	 * 2016-11-28
	 * 装修棋牌室
	 * */
	public function decorate_shop() {
		$id = I('id');
		$shopname = I('shopname');
		$ds = I('ds');
		$ds = str_replace("\n", "<br />", $ds);
		$phone = I('phone');
		$listimg = $this->uploadimgsy('listimg');
		$showimg = $this->uploadimgsy('showimg');
		$video = I('video');
		$data = array('shopname' => $shopname, 'ds' => $ds, 'phone' => $phone, 'listimg' => $listimg, 'showimg' => $showimg, 'video'=>$video);
		$res = M('shop')->where(array('id' => $id))->save($data);
		if ($res) {
			$this->ajaxReturn(array('s' => true, 'm' => "提交成功"));
		} else {
			$this->ajaxReturn(array('s' => false, 'm' => "提交失败"));
		}

	}

	/* *
	 * Nick
	 * 2016-12-5
	 * 图片组上传
	 * */
	public function uploadimg($key) {
		$imgData = I($key);
		if($imgData==""){
			return $imgData;
		}
		$imgData = explode("@", $imgData);

		$resutl = array();
		foreach ($imgData as $img) {
			$resutl[] = $this->saveOneImage($img);
		}
		$resutl = implode(',', $resutl);

		return $resutl;
	}
	
	/* *
	 * Nick
	 * 2016-12-5
	 * 图片组上传
	 * */
	public function uploadimgsy($key, $watermark = false) {
		$imgData = I($key);
		if($imgData==""){
			return $imgData;
		}
		$imgData = explode("@", $imgData);
		$resutl = array();
		foreach ($imgData as $img) {
			$resutl[] = $this->saveOneImagesy($img, $watermark);
		}
		$resutl = implode(',', $resutl);
		//P($resutl);
		return $resutl;
	}
	
	public function uploadimgs() {
		$imgData = I('images');
		if($imgData==""){
			return $imgData;
		}
		$imgData = explode("@", $imgData);
		$resutl = array();
		foreach ($imgData as $img) {
			$resutl[] = $this->saveOneImagesy($img);
		}
		$resutl = implode(',', $resutl);
		$this->ajaxReturn(array('s' => true, 'm' => "ok", 'imgs'=>$resutl));
	}

	
	/* *
	 * Nick
	 * 2016-12-5
	 * 图片组上传
	 * */
	public function uploadimgtow($key) {
		$imgData = $key;
		if($imgData==""){
			return $imgData;
		}
		$resutl = array();
		foreach ($imgData as $img) {
			$resutl[] = $this->saveOneImage($img);
		}
		$resutl = implode(',', $resutl);

		return $resutl;
	}

	/* *
	 * Nick
	 * 2016-12-5
	 * 图片保存
	 * */
	public function saveOneImage($dataString) {
		$img = explode(',', $dataString);
		$npath = '/'.C('UPLOAD_PATH').'/userimg/';
		$nfilename = date('Ymd_His') . '_' . mt_rand(1000, 9999);
		$newName = $npath . $nfilename . '.jpg';
		file_put_contents('.' . $newName, base64_decode($img[1]));
		return C("SiteUrl") . $newName;
	}
	
	/* *
	 * Nick
	 * 2016-12-5
	 * 图片保存
	 * */
	public function saveOneImagesy($dataString, $watermark = false) {
		$img = explode(',', $dataString);
		$npath = '/'.C('UPLOAD_PATH').'/userimg/';
		$nfilename = date('Ymd_His') . '_' . mt_rand(1000, 9999);
		$newName = $npath . $nfilename . '.jpg';
		file_put_contents('.' . $newName, base64_decode($img[1]));
		//P($newName);
		if($watermark){
			Watermark($newName); 
		}
		return C("SiteUrl") . $newName;
		
	}

	/* *
	 * Dragon
	 * 2016-11-28
	 * 获取默认地址
	 * */

	public function getmaddr() {
		$where['status'] = 1;
		$where['uid'] = $this->uid;
		$re = M('Addr')->where(array('uid' => $this->uid))->find();
		if (!$re) {
			$this->ajaxReturn(array('s' => false, 'd' => "没有地址"));
		}
		$res = M('Addr')->where($where)->find();

		if ($res) {
			$this->ajaxReturn(array('s' => true, 'd' => $res));
		} else {
			$this->ajaxReturn(array('s' => false));
		}

	}

	/*
	 * LiuZeMing
	 * 2016年12月5日15:39:49
	 * 贴吧
	 */
	//贴吧模块
	public function tie_model() {
		$res = M('category')->where('cid=1')->select();
		foreach ($res as $key => $value) {
			foreach (json_decode($value['cate_img']) as $v) {
				$res[$key]['cate_img'] = $v;
			}
		}
		if (false !== $res) {
			$this->ajaxReturn(array('s' => true, 'd' => $res));
		} else {
			$this->ajaxReturn(array('s' => false));
		}
	}

	//发帖
	public function add_tie() {
		$title = I('title');
		$content = I('content');
		$cid = I('cid');
		$img = $this->uploadimgsy('img');
		$uid = $this->uid;
		$ctime = time();
		$data = array('title' => $title,'img'=>$img, 'conten' =>base64_encode($content), 'uid' => $uid, 'cid' => $cid, 'ctime' => $ctime, );
		$res = M('bbs_info')->data($data)->add();
		if (false !== $res) {
			$this->ajaxReturn(array('s' => true));
		} else {
			$this->ajaxReturn(array('s' => false));
		}
	}

	//帖子列表
	public function tie_list() {
		$keyword = I('keyword');
		$cid = I('cid');
		//模板id
		$type = I('type');
		
		//1推荐  2最新
		if (!empty($cid)) {
			$where['status'] = 0;
			$where['cid'] = $cid;
			$res = M('bbs_info')->where($where)->order('zan desc')->select();
			$uid = $this->uid;
			foreach ($res as $key => $value) {
				$zan_where=array('bbs_id'=>$value['id'],'uid'=>$uid);
				$zan_have	=	M('bbs_zan')->where($zan_where)->find();
				if(!empty($zan_have)){
					$res[$key]['zan_status'] = 1;
				}else{
					$res[$key]['zan_status'] = 0;
				}
				if ($value['uid'] == $uid) {
					$res[$key]['status'] = 1;
				} else {
					$res[$key]['status'] = 2;
				}
				$userinfo = M('user')->where('id="' . $value['uid'] . '"')->find();
				//找到发帖人的用户信息/
				$category = M('category')->where('id="' . $value['cid'] . '"')->find();
				$res[$key]['cname'] = $category['category'];
				$res[$key]['nickname'] = $userinfo['nickname'];
				$res[$key]['conten'] =base64_decode($value['conten']);
				$res[$key]['age'] = $userinfo['age'];
				$res[$key]['sex'] = $userinfo['sex'];
				$res[$key]['phone'] = $userinfo['phone'];
				$res[$key]['img'] = $userinfo['img'];
				$res[$key]['sig'] = $userinfo['sig'];
				$res[$key]['ctime'] = date("Y-m-d H:i", $value['ctime']);
				$num = M('bbs_reply')->where('bbs_id="' . $value['id'] . '"')->count();
				$res[$key]['p_num'] = $num;
			}
			$cname_l = M('category')->find($cid);
			$cname = $cname_l['category'];
			$this->ajaxReturn(array('s' => true, 'd' => $res, 'n' => $cname));
		}
		if (!empty($type)) {
			if ($type == 1) {
				$res = M('bbs_info')->where('status=0')->order('zan desc')->select();
			}
			if ($type == 2) {
				$res = M('bbs_info')->where('status=0')->order('ctime desc')->select();
			}
		}
		if (!empty($keyword) && empty($type)) {
			$where['title'] = array('like', "%" . $keyword . "%");
			$where['status'] = 0;
			$res = M('bbs_info')->where($where)->order('ctime desc')->select();
		}
		if (empty($keyword) && empty($type) && empty($cid)) {
			$where['status'] = 0;
			$res = M('bbs_info')->where($where)->order('ctime desc')->select();
		}
		if (false !== $res) {
			$uid = $this->uid;
			foreach ($res as $key => $value) {
				if ($value['uid'] == $uid) {
					$res[$key]['status'] = 1;
				} else {
					$res[$key]['status'] = 2;
				}
				$zan_where=array('bbs_id'=>$value['id'],'uid'=>$uid);
				$zan_have	=	M('bbs_zan')->where($zan_where)->find();
				if(!empty($zan_have)){
					$res[$key]['zan_status'] = 1;
				}else{
					$res[$key]['zan_status'] = 0;
				}
				if ($value['uid'] == $uid) {
					$res[$key]['status'] = 1;
				} else {
					$res[$key]['status'] = 2;
				}
				$userinfo = M('user')->where('id="' . $value['uid'] . '"')->find();
				//找到发帖人的用户信息/
				$category = M('category')->where('id="' . $value['cid'] . '"')->find();
				$res[$key]['cname'] = $category['category'];
				$res[$key]['nickname'] = $userinfo['nickname'];
				$res[$key]['conten'] =base64_decode($value['conten']);
				$res[$key]['age'] = $userinfo['age'];
				$res[$key]['sex'] = $userinfo['sex'];
				$res[$key]['phone'] = $userinfo['phone'];
				$res[$key]['img'] = $userinfo['img'];
				$res[$key]['sig'] = $userinfo['sig'];
				$res[$key]['ctime'] = date("Y-m-d H:i", $value['ctime']);
				$num = M('bbs_reply')->where('bbs_id="' . $value['id'] . '"')->count();
				$res[$key]['p_num'] = $num;
			}
			$this->ajaxReturn(array('s' => true, 'd' => $res));
		} else {
			$this->ajaxReturn(array('s' => false));
		}
	}

	//帖子详情
	public function tie_info() {
		$id = I('id');
		$res = M('bbs_info')->where('id="' . $id . '"')->find();
		
		//帖子
		$num = M('bbs_reply')->where('bbs_id="' . $id . '"')->count();
		//评论数
		$category = M('category')->where('id="' . $res['cid'] . '"')->find();
		//类别
		$userinfo = M('user')->where('id="' . $res['uid'] . '"')->find();
		//找到发帖人的用户信息/
		$p_list = M('bbs_reply')->where('bbs_id="' . $id . '"')->select();
		//评论
		$list = array();
		$res['img']= explode(",", $res['img']);
		$list['data'] = $res;
		$list['data']['conten'] =base64_decode($res['conten']);
		$list['data']['p_num'] = $num;
		$list['data']['user'] = $userinfo['nickname'];
		$list['data']['user_img'] = $userinfo['img'];
		$list['data']['c_name'] = $category['category'];
		$list['data']['c_time'] = date("Y-m-d H:i", $res['ctime']);
		$list['p_data'] = array();
		foreach ($p_list as $key => $value) {
			$user = M('user')->where('id="' . $value['uid'] . '"')->find();
			$list['p_data'][$key]['nickname'] = $user['nickname'];
			$list['p_data'][$key]['img'] = $user['img'];
			$list['p_data'][$key]['bbs_id'] = $value['bbs_id'];
			$list['p_data'][$key]['content'] = base64_decode($value['content']);
			$list['p_data'][$key]['content_img']=explode(",", $value['img']);
			$list['p_data'][$key]['ctime'] = date("Y-m-d H:i", $value['ctime']);
		}
		$zan_where=array('bbs_id'=>$id,'uid'=>$this->uid);
		$zan_have	=	M('bbs_zan')->where($zan_where)->find();
		if(!empty($zan_have)){
			$list['data']['zan_status'] = 1;
		}else{
			$list['data']['zan_status'] = 0;
		}
		if (false !== $res && !empty($res)) {
			$this->ajaxReturn(array('s' => true, 'd' => $list));
		} else {
			$this->ajaxReturn(array('s' => false));
		}
	}

	//帖子删除
	public function tie_del() {
		$id = I('id');
		$uid = $this->uid;
		$res = M('bbs_info')->where(array('id' => $id))->find();
		$userid = $res['uid'];
		if ($uid == $userid) {
			$res = M('bbs_info')->where(array('id' => $id))->data(array('status' => 1))->save();
			if ($res) {
				$this->ajaxReturn(array('s' => true));
			} else {
				$this->ajaxReturn(array('s' => false));
			}
		}
	}

	//帖子评论
	public function tie_ping() {
		$bbs_id = I('bbs_id');
		$content = I('content');
		$img = $this->uploadimgsy('img');
		$uid = $this->uid;
		$data = array('bbs_id' => $bbs_id,'img'=>$img,'content' =>base64_encode($content), 'uid' => $uid, 'ctime' => time(), );
		$res = M('bbs_reply')->data($data)->add();
		if ($res !== false) {
			$this->ajaxReturn(array('s' => true));
		} else {
			$this->ajaxReturn(array('s' => false));
		}
	}

	//帖子点赞
	public function tie_zan() {
		$bbs_id = I('bbs_id');
		$uid = $this->uid;
		//判断是否点过赞
		$list_find = M('bbs_zan')->where(array('bbs_id' => $bbs_id, 'uid' => $uid))->find();
		if (!empty($list_find)) {
			$this->ajaxReturn(array('s' => false, 'd' => '', 'm' => "您已经赞过帖子"));
		}
		$list = M('bbs_info')->where('id="' . $bbs_id . '"')->find();
		$zan = $list['zan'];
		$data = array('zan' => $zan + 1, );
		$res = M('bbs_info')->where('id="' . $bbs_id . '"')->data($data)->save();
		$res_add = M('bbs_zan')->data(array('bbs_id' => $bbs_id, 'uid' => $uid))->add();
		if ($res && $res_add) {
			$this->ajaxReturn(array('s' => true, 'm' => "点赞成功"));
		} else {
			$this->ajaxReturn(array('s' => false, 'm' => "点赞失败"));
		}
	}

	/*
	 * LiuZeMing
	 * 2016年12月6日11:59:12
	 * 咨询
	 */
	//咨询首页
	public function model_index() {
		$where = ['cid'=>3];
		if($this->system){
			$where['systems'] = ['like', '%'.$this->system.'%'];
		}
		$res = M('category')->where($where)->order('id desc')->select();
		if (false !== $res) {
			$this->ajaxReturn(array('s' => true, 'd' => $res));
		} else {
			$this->ajaxReturn(array('s' => false));
		}
	}

	//资讯列表
	public function news_list() {
		$cid = I('cid');
		$page = I('page');
		$size = I('size');
		$where = ['cid'=>$cid];
		if($this->system){
			$where['systems'] = ['like', '%'.$this->system.'%'];
		}
		//模板id
		if (!empty($cid)) {
			if($page){
				$res = M('article')->where($where)->page($page, $size)->order('ctime desc')->select();
			}else{
				$res = M('article')->where($where)->order('ctime desc')->select();
			}
			foreach ($res as $key => $value) {

				$res[$key]['ctime'] = date('Y-m-d H:i:s', $value['ctime']);

				$a = strip_tags($value['content']);
				$res[$key]['n_con'] = mb_substr($a, 0, 20, "utf-8");
				$img_arr = json_decode($value['img']);
				foreach ($img_arr as $k => $v) {
					$res[$key]['img'] = $v;
				}
				if($cid == '86'){
					$res[$key]['img'] = implode(',', $img_arr);
				}
			}
		} else {
			$list = M('category')->order('id desc')->find();
			$id = $list['id'];
			if($page){
				$res = M('article')->where($where)->page($page, $size)->order('ctime desc')->select();
			}else{
				$res = M('article')->where($where)->order('ctime desc')->select();
			}
			foreach ($res as $key => $value) {
				$res[$key]['ctime'] = date('Y-m-d H:i:s', $value['ctime']);
				$a = strip_tags($value['content']);
				$res[$key]['n_con'] = mb_substr($a, 0, 20, "utf-8");
				foreach (json_decode($value['img']) as $k => $v) {
					$res[$key]['img'] = $v;
				}
			}
		}
		if (false !== $res) {
			$this->ajaxReturn(array('s' => true, 'd' => $res));
		} else {
			$this->ajaxReturn(array('s' => false));
		}
	}

	//资讯详情
	public function news_info() {
		$id = I('id');
		$res = M('article')->where('id="' . $id . '"')->find();
		if ($res['aid'] != 0) {
			$advertising = M('article_advertising')->where('id="' . $res['aid'] . '"')->find();
		}
		if($res['cid'] != 0){
			$res['category'] = M('category')->where(['id'=>$res['cid']])->getField('category');
		}else{
			$res['category'] = '';
		}
		$res['ctime'] = date("Y-m-d", $res['ctime']);
		foreach (json_decode($res['img']) as $va) {
			$res['img'] = $va;
		}
		foreach ($res as $value) {
			$res['a_title'] = !empty($advertising) ?  $advertising['title'] : '';
			$res['a_url'] = !empty($advertising) ?  $advertising['url'] : '';
			$res['a_desc'] = !empty($advertising) ?  $advertising['desc'] : '';
			// foreach (json_decode($advertising['img']) as $v) {
			// 	$res['a_img'] = $v;
			// }
			$res['a_img'] = $advertising['img'];
		}
		if (false !== $res && !empty($res)) {
			M('article')->where(['id'=>$id])->setInc('views', 1);
			$this->ajaxReturn(array('s' => true, 'd' => $res));
		} else {
			$this->ajaxReturn(array('s' => false));
		}
	}

	function array_sort($arr, $keys, $type = 'asc') {
		$keysvalue = $new_array = array();
		foreach ($arr as $k => $v) {
			$keysvalue[$k] = $v[$keys];
		}
		if ($type == 'asc') {
			asort($keysvalue);
		} else {
			arsort($keysvalue);
		}
		reset($keysvalue);
		foreach ($keysvalue as $k => $v) {
			$new_array[$k] = $arr[$k];
		}
		return $new_array;
	}
	
	
	
	
	//麻将馆三个置顶
	public function shop_listtop() {
		//纬度
		$where['area'] = I('ace');
		$where['status'] = '1';
		if($this->system){
			$where['systems'] = ['like', '%'.$this->system.'%'];
		}
		$list = M('shop')->where($where)->order('sort desc')->limit('3')-> select();
		//评论  以及评论图片
		$arr=array();
		foreach ($list as $k => $v) {
			$list_p = M("shop_reply")->where('s_id="' .$v['id'] . '"')->select();
			$p_num = count($list_p);
			foreach ($list_p as $key => $value) {
					$xing = $xing + $value['xing'];
				}
			$arr[$k]['xing']= ceil($xing / $p_num);
			$order_num = M('appointment')->where('shopid="' .$v['id']. '"')->count();
		
			$arr[$k]['order_num'] = count($list_p) + $order_num;
			$arr[$k]['shopname'] =$v['shopname'];
			$arr[$k]['area']=$v['area'];
			$arr[$k]['lng']=$v['lng'];
			$arr[$k]['lat']=$v['lat'];
			$arr[$k]['id']=$v['id'];
			$arr[$k]['listimg']=$v['listimg'];
		}
		if (false !== $list) {
			$this->ajaxReturn(array('s' => true, 'd' => $arr));
		} else {
			$this->ajaxReturn(array('s' => false));
		}
	}
	
	
	//麻将馆列表
	public function shop_list() {
		$type = I('type');
		$type = 4;
		$shop_type = I('shop_type');
		$lng = I('lng');
		//经度
		$lat = I('lat');
		//纬度
		$pro = I('pro');
		$city = I('city');
		if($pro){
			$where['pro'] = I('pro');
		}
		if($city){
			$where['city'] = I('city');
		}
		$where['area'] = I('ace');
		$where['status'] = '1';
		$key=I('key');
		if(!empty($key)){
			$where['shopname'] = array("like","%".$key."%");
		}
		if($shop_type){
			$where['shop_type']	= $shop_type;
		}
		if($this->system){
			$where['systems'] = ['like', '%'.$this->system.'%'];
		}
		switch ($type) {
			case '1' :
				//人气
				$list = M('shop')->where($where)->order('renqi desc')->select();
				
				break;
			case '2' :
				//评价
				$list = M('shop')->where($where)->order('pinglun desc')->select();
				
				break;
			case '3' :
				//综合
				$list = M('shop')->where($where)->select();
				foreach ($list as $k => $v) {
					$list_p = M("shop_reply")->where('s_id="' .$v['id'] . '"')->select();
					$p_num = count($list_p);
					foreach ($list_p as $key => $value) {
							$xing = $xing + $value['xing'];
						}
					$arr[$k]['xing']= ceil($xing / $p_num);
					$order_num = M('appointment')->where('shopid="' .$v['id']. '"')->count();
				
					$arr[$k]['order_num'] = count($list_p) + $order_num;
					$arr[$k]['shopname'] =$v['shopname'];
					$arr[$k]['area']=$v['area'];
					$arr[$k]['lng']=$v['lng'];
					$arr[$k]['lat']=$v['lat'];
					$arr[$k]['id']=$v['id'];
					$arr[$k]['is_discount_today']=$v['is_discount_today'];
					$arr[$k]['listimg']=$v['listimg'];
					
					$val = ($v['lng'] - $lng) * ($v['lng'] - $lng) + ($v['lat'] - $lat) * ($v['lat'] - $lat);
					$arr[$k]['ju'] = round(sqrt($val), 5);
				}
				$arr = $this->array_sort($arr, 'xing', 'desc');
				$returndata = array();
				foreach ($arr as $re) {
					$returndata[] = $re;
				}
				$arr = $returndata;
				// $this->ajaxReturn(array('s' => true, 'd' => $returndata));
				break;
			case '4' :
				//距离
				$list = M('shop')->where($where)->select();
				foreach ($list as $k => $v) {
					$list_p = M("shop_reply")->where('s_id="' .$v['id'] . '"')->select();
					$p_num = count($list_p);
					foreach ($list_p as $key => $value) {
							$xing = $xing + $value['xing'];
						}
					$arr[$k]['xing']= ceil($xing / $p_num);
					$order_num = M('appointment')->where('shopid="' .$v['id']. '"')->count();
				
					$arr[$k]['order_num'] = count($list_p) + $order_num;
					$arr[$k]['shopname'] =$v['shopname'];
					$arr[$k]['area']=$v['area'];
					$arr[$k]['lng']=$v['lng'];
					$arr[$k]['lat']=$v['lat'];
					$arr[$k]['id']=$v['id'];
					$arr[$k]['is_discount_today']=$v['is_discount_today'];
					$arr[$k]['listimg']=$v['listimg'];
					
					$val = ($v['lng'] - $lng) * ($v['lng'] - $lng) + ($v['lat'] - $lat) * ($v['lat'] - $lat);
					$arr[$k]['ju'] = round(sqrt($val), 5);
					
				}
				$arr = $this->array_sort($arr, 'ju');
				$returndata = array();
				foreach ($arr as $re) {
					$returndata[] = $re;
				}
				$arr = $returndata;
				// $this->ajaxReturn(array('s' => true, 'd' => $returndata));
			default :
				$where['sort'] = '0';
				$list = M('shop')->where($where)->select();
				foreach ($list as $k => $v) {
					$list_p = M("shop_reply")->where('s_id="' .$v['id'] . '"')->select();
					$p_num = count($list_p);
					foreach ($list_p as $key => $value) {
							$xing = $xing + $value['xing'];
						}
					$arr[$k]['xing']= ceil($xing / $p_num);
					$order_num = M('appointment')->where('shopid="' .$v['id']. '"')->count();
				
					$arr[$k]['order_num'] = count($list_p) + $order_num;
					$arr[$k]['shopname'] =$v['shopname'];
					$arr[$k]['area']=$v['area'];
					$arr[$k]['lng']=$v['lng'];
					$arr[$k]['lat']=$v['lat'];
					$arr[$k]['id']=$v['id'];
					$arr[$k]['is_discount_today']=$v['is_discount_today'];
					$arr[$k]['listimg']=$v['listimg'];
					
					$val = ($v['lng'] - $lng) * ($v['lng'] - $lng) + ($v['lat'] - $lat) * ($v['lat'] - $lat);
					$arr[$k]['ju'] = round(sqrt($val), 5);
				}
				$arr = $this->array_sort($arr, 'ju');
				$returndata = array();
				foreach ($arr as $re) {
					$returndata[] = $re;
				}
				$arr = $returndata;
				// $this->ajaxReturn(array('s' => true, 'd' => $returndata));
				break;
		}
		if(in_array($type, ['1', '2'])){
			//评论  以及评论图片
			foreach ($list as $k => $v) {
				$list_p = M("shop_reply")->where('s_id="' .$v['id'] . '"')->select();
				$p_num = count($list_p);
				foreach ($list_p as $key => $value) {
						$xing = $xing + $value['xing'];
					}
				$arr[$k]['xing']= ceil($xing / $p_num);
				$order_num = M('appointment')->where('shopid="' .$v['id']. '"')->count();
			
				$arr[$k]['order_num'] = count($list_p) + $order_num;
				$arr[$k]['shopname'] =$v['shopname'];
				$arr[$k]['area']=$v['area'];
				$arr[$k]['lng']=$v['lng'];
				$arr[$k]['lat']=$v['lat'];
				$arr[$k]['id']=$v['id'];
				$arr[$k]['is_discount_today']=$v['is_discount_today'];
				$arr[$k]['listimg']=$v['listimg'];
			}
		}
		if(!empty($arr)){

        	$amap_key = 'd7cdde040024dc1fe22157970ba6bd6b';
			$origins = '';
            foreach ($arr as $key => $row) {
                $origins.= ($origins ? "|":'').$row['lng'].','.$row['lat'];
            }

            $url = "http://restapi.amap.com/v3/assistant/coordinate/convert?key={$amap_key}&locations={$origins}&coordsys=baidu";
            $res = curl_get($url);
            $res = json_decode($res, true);
            $origins = '';
            if($res['status'] == '1'){
            	$locations = $res['locations'];
            	foreach (explode(';', $locations) as $key => $row) {
            		$origins.= ($origins ? "|":'').explode(',', $row)[0].','.explode(',', $row)[1];
            	}
            }
			$url = "http://restapi.amap.com/v3/assistant/coordinate/convert?key={$amap_key}&locations={$lng},{$lat}&coordsys=gps";
            $res = curl_get($url);
            $res = json_decode($res, true);
            if($res['status'] == '1'){
            	$lng = explode(',', $res['locations'])[0];
            	$lat = explode(',', $res['locations'])[1];
            }
            try{
                require_once 'ThinkPHP/Library/Vendor/autoload.php';
                $res = \yishuixm\lbs\LbsAmap::distance($amap_key, $origins, $lng.','.$lat, 1);
                $res = json_decode($res, true);
                if($res['status'] == 1){
                    foreach ($arr as $key => &$row) {
                        $row['ju'] = $res['results'][$key]['distance'];
                    }
                    if($type == '4' || $type == ''){
                    	array_multisort(array_column($arr, 'ju'), SORT_ASC, $arr);
                    }
                }
            }catch(\Exception $e){

            }
		}	

		if (false !== $list) {
			$arr = $arr ? $arr : [];
			$this->ajaxReturn(array('s' => true, 'd' => $arr));
		} else {
			$this->ajaxReturn(array('s' => false));
		}
	}

	//麻将馆详情
	public function shop_info() {
		$id = I('id');
		
		
		$list = M('shop')->field('card,boss_img,yyzz', true)->where('id="' . $id . '"')->find();
		$renqi = $list['renqi'] + 1;
		$res = M('shop')->where('id="' . $id . '"')->save(array('renqi' => $renqi));
		//人气+1

		$list['showimg'] = explode(',', $list['showimg']);
		if($list['ad_id']){
			$ad = M('article_advertising')->where(['id'=>$list['ad_id']])->find();
		}

		//评论  以及评论图片
		$list_p = M("shop_reply")->where('s_id="' . $id . '"')->select();
		$p_num = count($list_p);
		foreach ($list_p as $key => $value) {
			$list_p[$key]['ctime'] = date("Y-m-d H:i:s", $value['ctime']);
			//评论人信息
			$uid = $value['uid'];
			$user = M('user')->find($uid);
			if($value['content']){
				$list_p[$key]['content'] = base64_decode($value['content']);
			}
			$list_p[$key]['nickname'] = $user['nickname'];
			$list_p[$key]['head_img'] = $user['img'];
			$imgdata = explode(',', json_decode($value['img']));
			$list_p[$key]['ping_img'] = $imgdata;
			//评论星总和
			$xing = $xing + $value['xing'];
		}
		$list['xing'] = ceil($xing / $p_num);
		$list['pinglun_info'] = $list_p;
		
		
		//预订过的人数
		$order_num = M('appointment')->where('shopid="' . $id . '"')->count();
		$list['order_num'] = count($order_num);
		if (false !== $list) {
			// 管理软件
			$glrj = 0;
			if(($this->uid && $list['uid'] == $this->uid) || ($this->user && ($list['phone'] == $this->user['phone'] || $list['tel'] == $this->user['phone']))){
				$list['is_self'] = 1;
				$glrj = 1;
			}else{
				$list['is_self'] = 0;
				if($this->user){
					$hasStaff = M('shop_staff')->where(['shop_id'=>$list['id'], 'phone'=>$this->user['phone']])->find();
					if($hasStaff){
						$glrj = 1;
					}
				}
			}

            $siteurl = C("SiteUrl");
            $video_cover = '';
            if($list['video']){
	            require_once 'ThinkPHP/Library/Vendor/autoload.php';
	            $ffmpeg = new \Common\Util\FFMpeg();
	            $ffmpeg = $ffmpeg->ffmpeg;
	            $cover_path = './'.C('UPLOAD_PATH').'/videocover/';
	            if(!is_dir($cover_path)){
	                mkdir($cover_path, 0755, true);
	            }
                try {
                    // 视频路径
                    $video_path = str_replace($siteurl, './', $list['video']);
                    if(!is_file($video_path)){
                    	$video_path = str_replace('http://www.yuzhuli.com/', './', $list['video']);
                    }
                    if(is_file($video_path)){
                        $poster_path = $cover_path.md5($video_path).'.jpg';// 生成封面保存路径
                        if(!is_file($poster_path)){
                            $video = $ffmpeg->open($video_path);
                            $frame = $video->frame(\FFMpeg\Coordinate\TimeCode::fromSeconds(1));
                            $frame->save($poster_path, false);  
                        }
                        $video_cover = str_replace('/./', '/', $siteurl.$poster_path);
                    }
                } catch (\Exception $e) {
                    trace('生成图片失败:'.$e->getMessage(), 'error');
                }
            }

			$list['video_cover'] = $video_cover;
			$result = array('s' => true, 'd' => $list);
			if(!empty($ad)){
				$result['ad'] = $ad;
			}
			// 机麻采购
			$gmcg = M('nearby_shop')->where(['province'=>$list['pro'], 'city'=>$list['city'], 'district'=>$list['area'], 'is_gz'=>1, 'check_status'=>1, 'status'=>1])->field('id')->find();
			if(empty($gmcg)){
				$gmcg = null;
			}
			$result['gmcg'] = $gmcg;
			$result['glrj'] = $glrj;

			// 优惠券
	        $coupons = M('shop_coupons')->alias('sc')
	        ->join('__SHOP_COUPON_TPLS__ t ON sc.tpl_id=t.id', 'left')
	        ->where(['sc.shop_id'=>$list['id']])
	        ->field('sc.id,sc.title,sc.is_condition,sc.condition_amount,sc.discount_amount,sc.get_start_time,sc.get_end_time,sc.use_start_time,sc.use_end_time,sc.create_time,t.img')
	        ->select();
	        if($coupons){
	            foreach ($coupons as $key => &$coupon) {
	                $coupon['get_start_time'] = date('Y-m-d', $coupon['get_start_time']);
	                $coupon['get_end_time'] = date('Y-m-d', $coupon['get_end_time']);
	                $coupon['use_start_time'] = date('Y-m-d', $coupon['use_start_time']);
	                $coupon['use_end_time'] = date('Y-m-d', $coupon['use_end_time']);
                	$coupon['create_time'] = date('Y-m-d H:i:s', $coupon['create_time']);
	                $coupon['condition_amount'] = $coupon['condition_amount']*1;
	                $coupon['discount_amount'] = $coupon['discount_amount']*1;
	            }
	        }
			$result['coupons'] = $coupons;
	        // 商家模板
	        if($list['activity_tpl']){
	            $shopTpl = M('shop_activity_tpls')->where(['id'=>$list['activity_tpl']])->field('id,img')->find();
	            if($shopTpl){
	                $shopTpl['desc'] = $list['activity_desc'];
	            }
	        }
			$result['shopTpl'] = $shopTpl;
	        // 技师
        	$technician = M('shop_technician')->where(['shop_id'=>$list['id']])->field('id,serial_number,img,title,desc')->select();
        	$technician_arr = [];
        	if($list['jishiselect_1']){
				$technician_arr = array_merge($technician_arr, page_array(3, 1, $technician, 0));
        	}
        	if($list['jishiselect_2']){
				$technician_arr = array_merge($technician_arr, page_array(3, 2, $technician, 0));
        	}
        	if($list['jishiselect_3']){
				$technician_arr = array_merge($technician_arr, page_array(3, 3, $technician, 0));
        	}
			$result['technician'] = $technician_arr;
			$user_id = 0;
			$user_phone = '';
			if($list['uid']){
				$user_id = $list['uid'];
				$user = M('user')->where(['id'=>$user_id])->find();
				if($user){
					$user_phone = $user['phone'];
					// $user_id = $user['id'];
				}
			}else{
				if($list['phone']){
					$user = M('user')->where(['phone'=>$list['phone']])->find();
					if($user){
						$user_phone = $user['phone'];
						$user_id = $user['id'];
					}
				}
				if(empty($user_id) && $list['tel']){
					$user = M('user')->where(['phone'=>$list['tel']])->find();
					if($user){
						$user_phone = $user['phone'];
						$user_id = $user['id'];
					}
				}
			}
			$result['user_id'] = $user_id;
			$result['user_phone'] = $user_phone;
			$this->ajaxReturn($result);
		} else {
			$this->ajaxReturn(array('s' => false));
		}
	}

	//麻将馆评论
	public function shop_ping() {
		$id = I('id');
		$xing = I('xing');
		$con = I('content');
		$img = $this->uploadimg('img');
		$re = M('appointment')->where(array('id' => $id))->find();
		
		$data = array('xing' => $xing, 'content' => base64_encode($con), 's_id' => $re['shopid'], 'ctime' => time(), 'img' => json_encode($img), 'uid' => $this->uid, 'aid'=>$re['id']);
		$res = M('shop_reply')->add($data);

		//然后评论数加一
		$list = M('shop')->find($re['shopid']);
		$num_p = $list['pinglun'] + $xing;
		$res_save = M('shop')->where(array('id' => $re['shopid']))->data(array('pinglun' => $num_p))->save();
		if (false !== $res && false !== $list && false !== $res_save) {
		
			$this->ajaxReturn(array('s' => true));
		} else {
			$this->ajaxReturn(array('s' => false));
		}
	}

	//麻将馆预约
	public function shop_order() {
		$uid = $this->uid;
		$userinfo = M('user')->where('id="' . $uid . '"')->find();
		$person_num = trim(I('person_num'));
		$order_time = I('order_time');
		$phone = I('phone');
		$address = I('address');
		$shopid = I('shopid');
		$data = array('uid' => $uid, 'content' => "麻将馆预约", 'cid' => 1, 'ctime' => time(), 'order_time' => $order_time, 'name' => $userinfo['nickname'], 'phone' => $userinfo['phone'], 'address' => $address, 'shopid' => $shopid, 'type' => 1, 'num' => $person_num, );
		$res = M('appointment')->add($data);
		if (false !== $res) {
			$this->ajaxReturn(array('s' => true));
		} else {
			$this->ajaxReturn(array('s' => false));
		}
	}

	/* *
	 * Dragon
	 * 2016-12-10
	 * 棋牌室是否开启
	 * */
	public function shop_openup() {
		$uid = $this->uid;
		$type = I('type');
		$res = M('shop')->where(array('uid' => $uid))->save(array('status' => $type));
		if (false !== $res) {
			$this->ajaxReturn(array('s' => true));
		} else {
			$this->ajaxReturn(array('s' => false));
		}
	}

	/* *
	 * Dragon
	 * 2016-12-10
	 * 棋牌室是否开启
	 * */
	public function shop_onandup() {
		$uid = $this->uid;
		$res = M('shop')->where(array('uid' => $uid))->find();

		if (false !== $res) {
			$this->ajaxReturn(array('s' => true, 'd' => $res['status']));
		} else {
			$this->ajaxReturn(array('s' => false));
		}
	}

	/* *
	 * Dragon
	 * 2016-12-10
	 * 棋牌室预约
	 * */
	public function shop_yuyuelist() {
		$uid = $this->uid;
		$shops = M('shop')->where([['uid'=>$uid], ['phone'=>$this->user['phone']], ['tel'=>$this->user['phone']], '_logic'=>'OR'])->select();
		if ($shops) {
			$shopids = array_column($shops, 'id');
			$list = M('appointment')->where(array('type' => 1, 'shopid' => ['in', $shopids]))->select();
			$data = array();
			M('appointment')->where(array('type' => 1, 'shopid' => ['in', $shopids]))->save(['is_read'=>1]);
			foreach ($list as $key => $value) {
				$list[$key]['ctime'] = date("Y-m-d H:i:s", $value['ctime']);
			}
			$this->ajaxReturn(array('s' => true, 'd' => $list));
		} else {
			$this->ajaxReturn(array('s' => false));
		}
	}

	//预约历史
	public function shop_history() {
		$uid = $this->uid;
		$where['uid'] = $uid;
		$where['type'] = "1";
		$history = M('appointment')->where($where)->select();
		
		$res = array();
		foreach ($history as $key => $value) {
			$list = M('shop')->where('id="' . $value['shopid'] . '"')->find();
			$res[$key]['shopname'] = $list['shopname'];
			$res[$key]['addr'] = $list['pro'] . $list['city'] . $list['area'] . $list['addr'];
			//评论  以及评论图片
			try {
			$list_p = M("shop_reply")->where(array('aid'=>$value['id']))->find();
			} catch(Exception $e) {
				$this->ajaxReturn(array('s' => false, 'm' => '参数错误'));
			}
			if(empty($list_p)){
			$res[$key]['status']=0;//未评论
			}else{
			$res[$key]['status']=1;//已评论
			}
			$res[$key]['order_time']=$value['order_time'];
			$res[$key]['ctime']= date("Y-m-d H:i:s",$value['ctime']); 
			$res[$key]['nikcname']=$value['name'];
			$res[$key]['num']=$value['num'];
			$res[$key]['phone']=$value['phone'];
			$res[$key]['shopid']=$value['id'];
			
		}
		
		if (false !== $history) {
			$this->ajaxReturn(array('s' => true, 'd' => $res));
		}
		if (empty($history)) {
			$this->ajaxReturn(array('s' => true, 'm' => "没有预约过"));
		}
		if (false == $history) {
			$this->ajaxReturn(array('s' => false, 'm' => "意外错误"));
		}
	}

	//报修
	public function repair_order() {
		$uid = $this->uid;
		$name = I('name');
		$phone = I('phone');
		$content = I('content');
		$address = I('address');
		$data = array('uid' => $uid, 'content' => $content, 'cid' => 2, 'ctime' => time(), 'order_time' => time(), 'name' => $name, 'phone' => $phone, 'address' => $address, 'type' => 2);
		$res = M('appointment')->add($data);
		if (false !== $res) {
			$this->ajaxReturn(array('s' => true));
		} else {
			$this->ajaxReturn(array('s' => false));
		}
	}

	/**
	 * 商城
	 * 2016年12月7日10:56:50
	 * LiuZeM*/
	//商品列表
	public function pro_list() {
		
		$type = I('type');
		$cid=I('cid');
		$keyword = I('keyword');
		if (!empty($cid)) {
			$where['cid']=$cid;
		}
		if (!empty($keyword)) {
			$where['title'] = array('like', "%" . $keyword . "%");
		}
		if (empty($type)) {
			$type = 3;
		}
		$where['status'] = '1';
		switch ($type) {
			case '1' :
				//人气
				$list = M('product')->where($where)->field('showimg,content,ctime,status', true)->order('renqi desc')->select();
				foreach ($list as $key => $value) {
					foreach (json_decode($value['listimg']) as $v) {
						$list[$key]['listimg'] = $v;
					}
				}
				break;
			case '2' :
				//评价
				$list = M('product')->where($where)->field('showimg,content,ctime,status', true)->order('pinglun desc')->select();
				foreach ($list as $key => $value) {
					foreach (json_decode($value['listimg']) as $v) {
						$list[$key]['listimg'] = $v;
					}
				}
				break;
			case '3' :
				//销量
				$list = M('product')->where($where)->field('showimg,content,ctime,status', true)->order('sales desc')->select();
				foreach ($list as $key => $value) {
					foreach (json_decode($value['listimg']) as $v) {
						$list[$key]['listimg'] = $v;
					}
				}
				break;
			case '4' :
				//价格
				$list = M('product')->where($where)->field('showimg,content,ctime,status', true)->order('price desc')->select();
				foreach ($list as $key => $value) {
					foreach (json_decode($value['listimg']) as $v) {
						$list[$key]['listimg'] = $v;
					}
					$list[$key]['ctime'] = date("Y-m-d H:i:s", $value['ctime']);
				}
				break;
			default :
				$list = M('product')->where($where)->field('showimg,content,ctime,status', true)->order('renqi desc')->select();
				foreach ($list as $key => $value) {
					foreach (json_decode($value['listimg']) as $v) {
						$list[$key]['listimg'] = $v;
					}
				}
				break;
		}
		if (false !== $list) {
			$this->ajaxReturn(array('s' => true, 'd' => $list));
		} else {
			$this->ajaxReturn(array('s' => false));
		}
	}

	//购物车
	public function buy_car() {
		$pid = I('id');
		//商品
		$aid = I('aid');
		$atOnce = I('atOnce');
		//差价的id
		$uid = $this->uid;
		$num = I('num');
		$new = M('product_attr')->find($aid);
		//属性
		$list = M('product')->find($id);
		//商品
		$price = $list['price'];
		$dif = $new['dif'];
		$new_price = $price + $dif;
		$where = array('uid' => $uid, 'pid' => $pid, 'aid' => $aid);
		$rest = M('cart')->where($where)->find();
		if($yc_res_type = yc_buy_product_check($this->uid, $pid)){
			if($yc_res_type == 2){
				$this->ajaxReturn(array('s' => false, 'm'=>"购物车已存在一元产品，只能购买一件。"));
			}
			$this->ajaxReturn(array('s' => false, 'm'=>"您已购买过，只能购买一次。"));
		}
		if ($rest) {
			$outnum = $rest['num'];
			$newnum = $num + $outnum;
			if($atOnce){
				$newnum = $num;
			}
			if ($new['num'] < $newnum) {
				$newnum = $new['num'];
			}
			$all_price = $new_price * $newnum;
			$data = array('num' => $newnum, 'price' => $all_price);
			$res = M('cart')->where(array('id' => $rest['id']))->save($data);
			if ($res!==false) {
				$this->ajaxReturn(array('s' => true, 'd' => $rest['id']));
			} else {
				$this->ajaxReturn(array('s' => false));
			}
		} else {
			$all_price = $new_price * $num;
			if ($new['num'] < $num) {
				$num = $new['num'];
			}
			$data = array('uid' => $uid, 'pid' => $pid, 'aid' => $aid, 'price' => $all_price, 'num' => $num, 'ctime' => time(), );
			$res = M('cart')->add($data);

			if ($res) {
				$this->ajaxReturn(array('s' => true, 'd' => $res));
			} else {
				$this->ajaxReturn(array('s' => false));
			}
		}

	}

	/* *
	 * Dragon
	 * 2016-12-10
	 * 购物车结算数量更改
	 * */
	public function car_upnum() {
		$data = I("data");
		$arr = explode("_", $data);
		foreach ($arr as $key => $value) {
			$da = explode(":", $value);
			try {
				$res = M('cart')->where(array("id" => $da[0]))->save(array('num' => $da[1]));
			} catch(Exception $e) {
				$this->ajaxReturn(array('s' => false));
			}
		}
		$this->ajaxReturn(array('s' => true));
	}

	//购物车列表
	public function car_list() {
		$uid = $this->uid;
		//P($uid);
		$userinfo = M('user')->find($uid);
		$list = M('cart')->where(array('uid'=>$uid))->select();
		// $order = M('order')->where()->find();
		$cart_list = [];
		if($list){
			foreach ($list as $key => &$value) {
				$pro_info = M('product')->find($value['pid']);
				foreach (json_decode($pro_info['listimg']) as $v) {
					$value['listimg'] = $v;
				}
				$is_discount = 0;
				if($pro_info && $pro_info['cid']!=18){
					$is_discount = 1;
				}
				$value['is_discount'] = $is_discount;
				$value['price'] = $pro_info['price'];
				$value['ds'] = $pro_info['ds'];
				// $value['num'] = $value['num'];
				$attr = M('product_attr')->find($value['aid']);
				$value['attr_name'] = $attr['name'];
				$value['attr_dif'] = $attr['dif'];
				$value['attr_num'] = $attr['num'];
				$cart_list[] = $value;
			}
		}
		
		if (false !== $cart_list) {
			$this->ajaxReturn(array('s' => true, 'd' => $list));
		} else {
			$this->ajaxReturn(array('s' => false));
		}
	}

	//购物车多选付款
	public function check_more() {
		$id = I('id');
		if (is_array($id)) {
			foreach ($id as $value) {
				$price_list = M('cart')->find($value);
				$all_price = +$price_list['price'];
			}
		} else {
			$price_list = M('cart')->find($id);
			$all_price = $price_list['price'];
		}
		$this->ajaxReturn(array('s' => true, 'd' => $all_price));
	}

	//订单号
	public function order_num() {
		return date('Ymd') . substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
	}

	//商品评论
	public function pro_ping() {
		$id = I('id');
		$xing = I('xing');
		$con = I('content');
		$img = $this->uploadimg('img');
		$data = array('xing' => $xing, 'content' => $con, 's_id' => $id, 'ctime' => time(), 'img' => json_encode($img), 'uid' => $this->uid, );
		$res = M('pro_reply')->add($data);
		//然后评论数加一
		$list = M('product')->find($id);
		$num_p = $list['pinglun'] + 1;
		$res_save = M('product')->where('id="' . $id . '"')->data(array('pinglun' => $nup_p))->save();
		if (false !== $res && false !== $list && false !== $res_save) {
			$this->ajaxReturn(array('s' => true));
		} else {
			$this->ajaxReturn(array('s' => false));
		}
	}

	//商品详情
	public function pro_info() {
		$id = I('id');
		$res = M('product')->where('id="' . $id . '"')->find();
		$list['listimg'] = json_decode($res['listimg']);
		$list['showimg'] = json_decode($res['showimg']);
		$list['content'] = html_entity_decode($res['content']);
		$list['sales'] = $res['sales'];
		$list['price'] = $res['price'];
		$list['title'] = $res['title'];
		$list['ds'] = $res['ds'];
		$list['id'] = $id;
		$pro_attr = M('product_attr')->where('pid="' . $id . '"')->select();
		$list['pro_attr'] = $pro_attr;
		//属性

		//评论  以及评论图片
		$list_p = M("product_reply")->where('p_id="' . $id . '"')->select();
		$p_num = count($list_p);
		foreach ($list_p as $key => $value) {
			$list_p[$key]['ctime'] = date("Y-m-d H:i", $value['ctime']);
			$uid = $value['uid'];
			
			$user = M('user')->find($uid);
			$list_p[$key]['nickname'] = $user['nickname'];
			
			$list_p[$key]['head_img'] = $user['img'];
			$imgdata = explode(',', json_decode($value['img']));
			$list_p[$key]['ping_img'] = $imgdata;
			$list_p[$key]['content'] = base64_decode($value['content']);
		}
		$list['pinglun_info'] = $list_p;
		if (false !== $res) {
			$is_discount = 0;
			if($res['cid']!=18){
				$is_discount = 1;
			}
			$this->ajaxReturn(array('s' => true, 'd' => $list, 'is_discount'=>$is_discount));
		} else {
			$this->ajaxReturn(array('s' => false));
		}
	}

	/* *
	 * Dragon
	 * 2016-12-10
	 * 购物车id换详情
	 * */
	public function car_info() {
		$iddata = trim(I('id'));
		$idarr = explode("_", $iddata);
		//P($idarr,FALSE);
		$list = array();
		foreach ($idarr as $key => $value) {
			//P($value,FALSE);
			$res = M('cart')->where(array('id' => $value))->find();
			//echo M()->_sql();exit;
			if (!$res) {
				$this->ajaxReturn(array('s' => false, 'm' => '下单失败'));
			}
			$pid = $res['pid'];
			$aid = $res['aid'];
			$pro_info = M('product')->find($pid);
			if (!$pro_info) {
				$this->ajaxReturn(array('s' => false, 'm' => '商品不存在'));
			}
			$is_discount = 0;
			if($pro_info && $pro_info['cid']!=18){
				$is_discount = 1;
			}
			$list[$key]['is_discount'] = $is_discount;
			$pro_attr = M('product_attr')->find($aid);
			if (!$pro_attr) {
				$this->ajaxReturn(array('s' => false, 'm' => '类型不存在'));
			}
			foreach (json_decode($pro_info['listimg']) as $value) {
				$pro_info['listimg'] = $value;
			}
			$list[$key]['listimg'] = $pro_info['listimg'];
			$list[$key]['title'] = $pro_info['title'];
			$list[$key]['ds'] = $pro_info['ds'];
			$list[$key]['num'] = $res['num'];
			$list[$key]['pid'] = $pro_info['id'];
			$list[$key]['arrt'] = $pro_attr['name'];
			$list[$key]['pric'] = $pro_attr['dif'] + $pro_info['price'];

		}

		$this->ajaxReturn(array('s' => true, 'd' => $list));

	}

	/* *
	 * Dragon
	 * 2016-12-10
	 * 购物车删除
	 * */
	public function del_car() {
		$listid = I('listid');
		//P($listid);
		$uid = $this->uid;
		$where['uid'] = $uid;
		$str = true;
		foreach ($listid as $key => $value) {
			$where['id'] = $value;
			$res = M('cart')->where($where)->delete();
			if (!$res) {
				$str = false;
			}
		}
		if ($str) {
			$this->ajaxReturn(array('s' => true));
		} else {
			$this->ajaxReturn(array('s' => false));
		}
	}

	/* *
	 * Dragon
	 * 2016-12-12
	 * 添加订单
	 * */
	public function add_order() {
		$uid = $this->uid;
		$addid = I("addid");
		$cpric = I("cpric");// 支付金额
		$total_amount = I('total_amount', 0);// 总价
		$discount_amount = I('discount_amount', 0);// 优惠金额
		$distribution_amount = 0;
		$is_new = I('is_new');

		if(empty($total_amount)){
			$total_amount = $cpric;
		}
		$cid = trim(I('cid'));
		$idarr = explode("_", $cid);
		$addr = M('addr')->where(array('id' => $addid))->find();

		if($is_new){
			$total_amount = 0;
			$discount = product_discount();
			$is_buy_tea = 0;
			$cpric = 0;
			foreach ($idarr as $key => $value) {
				$res = M('cart')->where(array('id' => $value))->find();
				$pid = $res['pid'];
				$aid = $res['aid'];
	            $product = M('product')->where(array('id' => $pid))->find();
				$product_attr=M('product_attr')->where(array('id'=>$aid))->find();
	            $goods_price = $product_attr['dif']+$product['price'];
	            $is_buy = product_is_buy($uid, $pid);
				if(yc_buy_product_check($this->uid, $pid) === true){
					$this->ajaxReturn(['s' => false, 'm'=>"只能购买一次，您之前已购买过，无法再次购买"]);
				}
	            if($is_buy){
	            	$goods_item_total_price = round($discount*$goods_price*$res['num'], 2);
	            }else{
            		if($product['cid'] == 18){
            			$goods_item_total_price = round($goods_price*$res['num'], 2);
        			}else{
		            	if($res['num'] > 1){
		            		if($is_buy_tea){
		            			$goods_item_total_price = round($discount*$goods_price*$res['num'], 2);
		            		}else{
		            			$goods_item_total_price = round($discount*$goods_price*($res['num'] - 1)+$goods_price, 2);
		            		}
		            	}else{
		            		if($is_buy_tea){
	            				$goods_item_total_price = round($discount*$goods_price*$res['num'], 2);
		            		}else{
	            				$goods_item_total_price = round($goods_price*$res['num'], 2);
		            		}
		            	}
	            		$is_buy_tea = 1;
        			}
	            }
	            $cpric += $goods_item_total_price;
				if($product['cid'] != 18){
					$distribution_amount += $goods_item_total_price;
				}
	            $total_amount += $goods_price*$res['num'];
			}
		}
		$discount_amount = $total_amount - $cpric;

		//地址
		$odata = array(
			'uid' 				=> $uid,
			'code' 				=> $this->order_num(), //订单编号
			'c_name' 			=> $addr['c_name'], //收货人
			'c_phone' 			=> $addr['c_phome'], //收货人电话
			'c_addr' 			=> $addr['city'] . $addr['pro'] . $addr['area'] . $addr['add'], //收货人地址
			'cprice' 			=> $cpric, //总价
			'total_amount'		=> $total_amount,
			'discount_amount'	=> $discount_amount,
			'distribution_amount'	=> $distribution_amount,
			'ctime' 			=> time(), //创建时间
		);

		M()->startTrans();
		$orderModel = M('order');
		$odata = $orderModel->add($odata);
		$code = $orderModel->find($odata);
		$codes = $code['code'];
		if ($odata) {
			foreach ($idarr as $key => $value) {
				$res = M('cart')->where(array('id' => $value))->find();
				$pid = $res['pid'];
				$aid = $res['aid'];
				$product=M('product_attr')->where(array('id'=>$aid))->find();
				$onum=$product['num']-$res['num'];
				if($onum<0){
					M()->rollback();
					$this->ajaxReturn(array('s' => false, 'm' => '库存不足'));
				}
				$attrnum=array('num'=>$onum);
				try {
					M('product_attr')->where(array('id'=>$aid))->data($attrnum)->save();
				} catch(Exception $e) {
					M()->rollback();
					$this->ajaxReturn(array('s' => false));
				}
				if (!$res) {
					M()->rollback();
					$this->ajaxReturn(array('s' => false, 'm' => '下单失败'));
				}
				
				$data = array("pid" => $res['pid'], "aid" => $res['aid'], "code" => $codes, "num" => $res['num'], );
				try {
				 	M('order_info')->add($data);
				} catch(Exception $e) {
					M()->rollback();
					$this->ajaxReturn(array('s' => false));
				}
			}
			try {
				M('cart')->where(array("id" => array("in", $idarr)))->delete();
			} catch(Exception $e) {
				M()->rollback();
				$this->ajaxReturn(array('s' => false));
			}
			M()->commit();
			$this->ajaxReturn(array('s' => true, 'm' => '下单成功', 'd' => $codes));
		} else {
			M()->rollback();
			$this->ajaxReturn(array('s' => false, 'm' => '下单成功'));
		}
	}

	/* *
	 * Dragon
	 * 2016-12-14
	 * 获取全部订单
	 * */
	public function list_order() {
		$uid = $this->uid;
		$res = M('order')->where(array('uid' => $uid))->order('ctime desc')->select();

        $time = time() - 86400*7;
		foreach ($res as $key => $value) {
			$code = $value['code'];
			$orderInfo = M("order_info")->where(array('code' => $code))->select();
			foreach ($orderInfo as $k => $v) {
				$pdata = M('product')->where(array('id' => $v['pid']))->find();
				$pdata['listimg'] = json_decode($pdata['listimg']);
				$adata = M('product_attr')->where(array('id' => $v['aid']))->find();
				$data[$k]['listimg'] = $pdata['listimg'][0];
				$data[$k]['num'] = $v['num'];
				$data[$k]['pid'] = $v['pid'];
				$data[$k]['title'] = $pdata['title'];
				$data[$k]['ds'] = $pdata['ds'];
				$data[$k]['pirc'] = intval($adata['dif']) + intval($pdata['price']);
				$data[$k]['attr'] = $adata['name'];
			}
			$refund_btn = 0;
			$return = M('return')->where(['order_id'=>$value['id']])->find();
			if($value['pay_status'] == 1 && $value['status'] == 1){
				// 已付款 待发货
				if(empty($return) || $return['status'] == 3){
					$refund_btn = 1;// 售前退款按钮
				}
			}
			// 物流
			$logistics = logistics_com($value['logistics_type']);
			if($logistics){
				$res[$key]['logistics_com'] = $logistics['com'];
			}else{
				$res[$key]['logistics_com'] = '';
			}

			$res[$key]['refund_btn'] = $refund_btn;
			$return_btn = 0;
			if($value['pay_status'] == 1 && in_array($value['status'], ['2', '3', '4'])){
				// 已付款 已发货
				if(empty($return) || $return['status'] == 3){
					if(empty($value['receipt_time']) || $value['receipt_time'] > $time){
						$return_btn = 1;// 售后退货按钮
					}
				}
			}
			// 退货物流按钮
			$return_wl_btn = 0;
			if($return){
				if($return['refund_type'] == 2	&& $return['status'] == 2){
					$return_wl_btn = 1;
				}
			}
			// 退款详情
			$return_info_btn = 0;
			if($return && in_array($return['status'], ['4', '5'])){
				$return_info_btn = 1;
			}
			$res[$key]['return_id'] = $return ? $return['id'] : 0;
			$res[$key]['return_status'] = $return ? $return['status'] : 0;
			$res[$key]['return_btn'] = $return_btn;
			$res[$key]['return_wl_btn'] = $return_wl_btn;
			$res[$key]['return_info_btn'] = $return_info_btn;

			$res[$key]['data'] = $data;

		}
		if ($res) {
			$this->ajaxReturn(array('s' => true, 'd' => $res));
		} else {
			$this->ajaxReturn(array('s' => false));
		}

	}

	/* *
	 * Dragon
	 * 2016-12-14
	 * 获取一个详细订单
	 * */
	public function one_order() {
		$uid = $this->uid;
		$code = I('code');

		$res = M('order')->where(array('code' => $code))->find();
		$orderInfo = M("order_info")->where(array('code' => $res['code']))->select();
		foreach ($orderInfo as $k => $v) {
			$pdata = M('product')->where(array('id' => $v['pid']))->find();
			$pdata['listimg'] = json_decode($pdata['listimg']);
			$adata = M('product_attr')->where(array('id' => $v['aid']))->find();
			$data[$k]['listimg'] = $pdata['listimg'][0];
			$data[$k]['num'] = $v['num'];
			$data[$k]['title'] = $pdata['title'];
			$data[$k]['ds'] = $pdata['ds'];
			$data[$k]['pirc'] = intval($adata['dif']) + intval($pdata['price']);
			$data[$k]['attr'] = $adata['name'];
		}
		$res['data'] = $data;

		if ($res) {
			$this->ajaxReturn(array('s' => true, 'd' => $res));
		} else {
			$this->ajaxReturn(array('s' => false));
		}

	}

	/* *
	 * Dragon
	 * 2016-12-14
	 * 取消订单
	 * */
	public function cancel_order() {
		$uid = $this->uid;
		$code = I('code');

		$res = M('order')->where(array('code' => $code))->save(array('status' => 5));

		if ($res) {
			$this->ajaxReturn(array('s' => true));
		} else {
			$this->ajaxReturn(array('s' => false));
		}

	}

	/* *
	 * Dragon
	 * 2016-12-14
	 * 删除订单
	 * */
	public function del_order() {
		$uid = $this->uid;
		$code = I('code');
		$res = M('order')->where(array('code' => $code))->delete();

		if ($res) {
			$re = M('order_info')->where(array('code' => $code))->delete();
			if ($re) {
				$this->ajaxReturn(array('s' => true));
			} else {
				$this->ajaxReturn(array('s' => false));
			}
		} else {
			$this->ajaxReturn(array('s' => false));
		}

	}

	/* *
	 * Dragon
	 * 2016-12-14
	 * 确认收货
	 * */
	public function confirm_good() {
		$uid = $this->uid;
		$code = I('code');
		$order = M('order')->where(array('code' => $code))->find();
		$res = M('order')->where(array('code' => $code))->save(array('status' => 3,"read_status"=>0));

		if ($res) {
			if($order){
            	confirm_order_receipt($order['id']);
			}
			$this->ajaxReturn(array('s' => true));
		} else {
			$this->ajaxReturn(array('s' => false));
		}

	}

	/* *
	 * Dragon
	 * 2016-12-14
	 * 支付成功改状态
	 * */
	public function up_order_status() {
		$code = I('code');
		$res = update_pay_status($code);
		$this->ajaxReturn($res);
	}

	/**
	 *环信用户信息
	 * 2016年12月12日16:07:58
	 * liuzm */
	public function msg_user() {
		$uid = $this->uid;
		$user_info = M('user')->find($uid);
		$friend_list = I('friend_phone');
		$list['userinfo'] = $user_info;
		foreach ($friend_list as $value) {
			$f_list = M('user')->where('phone="' . $value . '"')->select();
			foreach ($f_list as $k => $v) {
				foreach (json_decode($v['img']) as $val) {
					$f_list[$k]['img'] = $val;
				}
			}
		}
		$list['friend'] = $f_list;
		if (empty($user_info)) {
			$this->ajaxReturn(array('s' => false, 'm' => '用户信息不合法'));
		} else {
			$this->ajaxReturn(array('s' => true, 'd' => $list));
		}
	}

	//获取订单详细信息
	public function orderInfo() {
		$uid = $this->uid;
		$type = I('type');
		$res = M('order')->where(array('status' => $type))->find();

		$orderInfo = M("order_info")->where(array('code' => $res['code']))->select();

		$res['data'] = $orderInfo;

		if ($res) {
			$this->ajaxReturn(array('s' => true, 'd' => $res));
		} else {
			$this->ajaxReturn(array('s' => false));
		}
	}

	/*	private $conf = array(
	 'notify_url'	=>	'http://mov30.weixinzjit.com/V3/Alipay/notify',
	 'return_url'	=>	'http://mov30.weixinzjit.com/V3/Alipay/returnurl',
	 'seller_email'	=>	'468569398@qq.com',
	 'partner'	=>	'2088421929396603',
	 'key'		=>	'lo1napa166wkv3m5r10clhbu81zmb6gh',
	 'privateKey' => '/home/wwwroot/yzl.lxrbk.com/cert/rsa_private_key.pem',
	 'publicKey' => '/home/wwwroot/yzl.lxrbk.com/cert/rsa_public_key.pem',
	 );*/

	 // 201870411之前
	// private $conf = array(
	// 'notify_url' => 'http://mov30.weixinzjit.com/V3/Alipay/notify', 
	// 'return_url' => 'http://mov30.weixinzjit.com/V3/Alipay/returnurl',
	// 'seller_email' => '468569398@qq.com',
 // 	'partner' => '2088421929396603', 
	// 'key' => 'lo1napa166wkv3m5r10clhbu81zmb6gh',
	// 'privateKey' => '/home/www/www.yuzhuli.com/cert/rsa_private_key.pem',
	// 'publicKey' => '/home/www/www.yuzhuli.com/cert/rsa_public_key.pem',
	// 'wechat' => array(
	// 	'appid' => "wx8ad67c23dbc02e0f",
	// 	'mch_id' => "1428672002",
	// 	'api_key' => "a0ea023a3bea4a172f327896490c31af",
	// 	'notify_url' => 'http://www.yuzhuli.com/V3/Alipay/notify',
	//     ),
	// );
	// 阳光牌友支付宝
	// appid 2018032802462151
	// seller_email 13524625822@139.com
	// partner 2088031711750913

	// private $conf = array(
	// 	'notify_url' => 'http://www.yuzhuli.com/api.php/Pay/ali_notify', 
	// 	'return_url' => 'http://mov30.weixinzjit.com/V3/Alipay/returnurl',
	// 	'seller_email' => '13524625822@139.com',
	//  	'partner' => '2088031711750913', 
	// 	'key' => 'lo1napa166wkv3m5r10clhbu81zmb6gh',
	// 	'privateKey' => '/home/www/www.yuzhuli.com/cert/rsa_private_key.pem',
	// 	'publicKey' => '/home/www/www.yuzhuli.com/cert/rsa_public_key.pem',
	// 	'wechat' => array(
	// 		'appid' => "wx9ec9195e80e812da",
	// 		'mch_id' => "1502288031",
	// 		'api_key' => "a0ea023a3bea4a172f327896490c31af",
	// 		'notify_url' => 'http://www.yuzhuli.com/api.php/Pay/notify',
	// 	    ),// 记得Common/Conf/config.php 里也对应修改
	// );

	public function wechat_js_config()
	{
		$url = I('url');
		$debug = I('debug');
        $APIs = I('apis');//['onMenuShareAppMessage', 'onMenuShareTimeline', 'onMenuShareQQ', 'onMenuShareWeibo', 'onMenuShareQZone', 'previewImage'];
        if(empty($url)){
			$this->ajaxReturn(array('s' => false, 'm' => 'url参数错误'));
        }
        if(empty($APIs) || !is_array($APIs)){
			$this->ajaxReturn(array('s' => false, 'm' => 'apis参数错误'));
        }
        $debug = $debug=='true' ? true : false;
        $wechat = new WeChatController();
        $js_config = $wechat->js_config($APIs, $debug, htmlspecialchars_decode($url));
		$this->ajaxReturn(array('s' => true, 'm'=>'ok', 'config' => $js_config));
	}

	/**
	 * 获取支付参数
	 * @return
	 */
	public function getParm() {
		$ordercode = I('ordercode');
		$trade_type = I('trade_type', 'app');
		if (empty($ordercode)) {
			$this->ajaxReturn(array('s' => false, 'm' => "order is null"));
		}
		if(strpos($ordercode, 'JC')!==false){
			// 集采订单
			$orderinfo = M('jc_order')->where(['order_sn'=>$ordercode])->find();
			if(!$orderinfo) {
				$this->ajaxReturn(['s' => false, 'm' => "getorder is no"]);
			}
			if($orderinfo['pay_status']){
				$this->ajaxReturn(['s' => false, 'm' => "订单已支付"]);
			}
			$body = '订单编号：'.$ordercode;
			$tade_no = $ordercode;
			$subject = $ordercode;
			$total_fee = $orderinfo['pay_money'];
		}else if(strpos($ordercode, 'JP')!==false){
			// 精辟话术
			$orderinfo = M('jp_talk_order')->where(['order_sn'=>$ordercode])->find();
			if(!$orderinfo) {
				$this->ajaxReturn(['s' => false, 'm' => "getorder is no"]);
			}
			if($orderinfo['pay_status']){
				$this->ajaxReturn(['s' => false, 'm' => "订单已支付"]);
			}
			$body = '订单编号：'.$ordercode;
			$tade_no = $ordercode;
			$subject = $ordercode;
			$total_fee = $orderinfo['pay_money'];
			M('jp_talk_order')->where(['order_sn'=>$ordercode])->save(['pay_method'=>'ali_app']);
		}else if(strpos($ordercode, 'ZX')!==false){
			// 情感咨询师
			$orderinfo = M('counselor_order')->where(['order_sn'=>$ordercode])->find();
			if(!$orderinfo) {
				$this->ajaxReturn(['s' => false, 'm' => "getorder is no"]);
			}
			if($orderinfo['pay_status']){
				$this->ajaxReturn(['s' => false, 'm' => "订单已支付"]);
			}
			$body = '订单编号：'.$ordercode;
			$tade_no = $ordercode;
			$subject = $ordercode;
			$total_fee = $orderinfo['pay_money'];
			M('counselor_order')->where(['order_sn'=>$ordercode])->save(['pay_method'=>'ali_app']);
		}else{
			$orderinfo = $this->getOrderInfo($ordercode);
			if(!$orderinfo) {
				$this->ajaxReturn(array('s' => false, 'm' => "getorder is no"));
			}
			$subject = $orderinfo['title'];
			$body = $orderinfo['orderids'];
			$total_fee = intval($orderinfo['money']);
			M('order')->where(['code'=>$ordercode])->save(['pay_method'=>'ali_app']);
		}
		if($this->uid==7602){
			$total_fee = 0.01;
		}
		$alipay = C('alipay');
		switch ($trade_type) {
			case 'app':
				$parameter = array(
					'service' 		=> 'mobile.securitypay.pay', // 必填，接口名称，固定值
					'partner' 		=> $alipay['partner'], // 必填，合作商户号
					'_input_charset'=> 'utf-8', // 必填，参数编码字符集
					'seller_id' 	=> $alipay['seller_email'], // 必填，卖家支付宝账号
					'payment_type' 	=> 1, // 必填，支付类型
					'out_trade_no' 	=> $ordercode, // $ordercode,      // 必填，商户网站唯一订单号
					'subject' 		=> $subject, // 必填，商品名称
					'body' 			=> $body, // 必填，商品详情
					'total_fee' 	=> $total_fee,    // 必填，总金额，取值范围为[0.01,100000000.00]
					// 'total_fee' 	=> 10, //测试的时候使用，更新生产的话把这行删除， 把上行注释去掉
					'notify_url' 	=> $alipay['notify_url'], // 可选，服务器异步通知页面路径
					// 'it_b_pay'    	=> '1d',        // 可选，未付款交易的超时时间
					// 'show_url'    	=> $base_path   // 可选，商品展示网站
				);
				$pp = $this->paraFilter($parameter);
				$ppa = $this->argSort($pp);
				$parameter['sign'] = $this->rsaSign($this->createLinkstring($ppa), $alipay['privateKey']);
				$parameter['sign_type'] = 'RSA';
				$aa = $this->createLinkstringUrlencode($parameter);
				$this->ajaxReturn(array('s' => true, 'd' => $aa));
				break;
			case 'wap':// 手机网页支付
				require_once 'ThinkPHP/Library/Vendor/autoload.php';
                $pay = new \Common\Util\Pay();
                $url = $pay->ali([
		            'use_sandbox'               => false,// 是否使用沙盒模式
		            'app_id'                    => $alipay['wap']['app_id'],
		            'sign_type'                 => 'RSA2',// RSA  RSA2
		            // ！！！注意：如果是文件方式，文件中只保留字符串，不要留下 -----BEGIN PUBLIC KEY----- 这种标记
		            // 可以填写文件路径，或者密钥字符串  当前字符串是 rsa2 的支付宝公钥(开放平台获取)
		            'ali_public_key'            => $alipay['wap']['ali_public_key'],
		            // 可以填写文件路径，或者密钥字符串  我的沙箱模式，rsa与rsa2的私钥相同，为了方便测试
		            'rsa_private_key'           => $alipay['wap']['rsa_public_key'],
		            // 与业务相关参数
		            'notify_url'                => U('Pay/wap_ali_notify', [], true, true),
		            'return_url'                => 'http://www.yuzhuli.com/h5/index.html',
		            'return_raw'                => false,// 在处理回调时，是否直接返回原始数据，默认为 true
		        ])->run(\Payment\Config::ALI_CHANNEL_WAP, [
                    'body'              => $body,
                    'subject'           => $subject,
                    'order_no'          => $ordercode,
                    'timeout_express'   => time() + 600,// 表示必须 600s 内付款
                    'amount'            => $total_fee,//$order['order_amount'],// 单位为元 ,最小为0.01
                    'return_param'      => '',// 一定不要传入汉字，只能是 字母 数字组合
                    'client_ip'         => getIP(),// 客户地址
                    'goods_type'        => '1',// 0—虚拟类商品，1—实物类商品
                    'store_id'          => '',
                    'quit_url'          => "https://www.yuzhuli.com/h5/index.html", // 收银台的返回按钮（用户打断支付操作时返回的地址,4.0.3版本新增）
                ]);
                $this->ajaxReturn(array('s' => true, 'd' => $url));
				// require_once VENDOR_PATH.'alipay.trade.wap.pay/wappay/service/AlipayTradeService.php';
				// require_once VENDOR_PATH.'alipay.trade.wap.pay/wappay/buildermodel/AlipayTradeWapPayContentBuilder.php';
				// $config = [
				// 	'app_id' => $alipay['app_id'],//应用ID,您的APPID。
				// 	'merchant_private_key' => str_replace(PHP_EOL, '', trim(file_get_contents($alipay['privateKeyStr']))),//商户私钥，您的原始格式RSA私钥
				// 	'notify_url' => $alipay['notify_url'],//异步通知地址
				// 	'return_url' => $alipay['return_url'],//同步跳转
				// 	'charset' => "UTF-8",//编码格式
				// 	'sign_type'=>"RSA2",//签名方式
				// 	'gatewayUrl' => "https://openapi.alipay.com/gateway.do",//支付宝网关
				// 	//支付宝公钥,查看地址：https://openhome.alipay.com/platform/keyManage.htm 对应APPID下的支付宝公钥。
				// 	'alipay_public_key' => str_replace(PHP_EOL, '', trim(file_get_contents($alipay['publicKeyStr']))),
				// ];
			 //    //商户订单号，商户网站订单系统中唯一订单号，必填
			 //    $out_trade_no = $ordercode;
			 //    //订单名称，必填
			 //    $subject = $subject;
			 //    //付款金额，必填
			 //    $total_amount = $total_fee;
			 //    //商品描述，可空
			 //    $body = "123";//$body;
			 //    //超时时间
			 //    $timeout_express = "5m";

			 //    $payRequestBuilder = new \AlipayTradeWapPayContentBuilder();
			 //    $payRequestBuilder->setBody($body);
			 //    $payRequestBuilder->setSubject($subject);
			 //    $payRequestBuilder->setOutTradeNo($out_trade_no);
			 //    $payRequestBuilder->setTotalAmount($total_amount);
			 //    $payRequestBuilder->setTimeExpress($timeout_express);
			 //    $payResponse = new \AlipayTradeService($config);
			 //    $result = $payResponse->wapPay($payRequestBuilder, $config['return_url'], $config['notify_url']);
				// $this->ajaxReturn(array('s' => true, 'd' => $result, 'config'=>$config));
				break;
			default:
				break;
		}
	}

	public function getWechatParm() {
		$ordercode = I('ordercode');
		$trade_type = I('trade_type', 'APP');
		Vendor("Pay.Wxpay.WxPayHelper");
		//获取订单数据
		if (empty($ordercode)) {
			$this->ajaxReturn(array('s' => false, 'm' => "order is null"));
		}
		if(strpos($ordercode, 'JC')!==false){
			// 集采订单
			$orderinfo = M('jc_order')->where(['order_sn'=>$ordercode])->find();
			if(!$orderinfo) {
				$this->ajaxReturn(['s' => false, 'm' => "getorder is no"]);
			}
			if($orderinfo['pay_status']){
				$this->ajaxReturn(['s' => false, 'm' => "订单已支付"]);
			}
			$orderBody = '订单编号：'.$ordercode;
			$tade_no = $ordercode;
			$attach = $ordercode;
			$total_fee = $orderinfo['pay_money']*100;
		}else if(strpos($ordercode, 'JP')!==false){
			// 精辟话术
			$orderinfo = M('jp_talk_order')->where(['order_sn'=>$ordercode])->find();
			if(!$orderinfo) {
				$this->ajaxReturn(['s' => false, 'm' => "getorder is no"]);
			}
			if($orderinfo['pay_status']){
				$this->ajaxReturn(['s' => false, 'm' => "订单已支付"]);
			}
			$orderBody = '订单编号：'.$ordercode;
			$tade_no = $ordercode;
			$attach = $ordercode;
			$total_fee = $orderinfo['pay_money']*100;
			M('jp_talk_order')->where(['order_sn'=>$ordercode])->save(['pay_method'=>'wx_app']);
		}else if(strpos($ordercode, 'ZX')!==false){
			// 情感咨询师
			$orderinfo = M('counselor_order')->where(['order_sn'=>$ordercode])->find();
			if(!$orderinfo) {
				$this->ajaxReturn(['s' => false, 'm' => "getorder is no"]);
			}
			if($orderinfo['pay_status']){
				$this->ajaxReturn(['s' => false, 'm' => "订单已支付"]);
			}
			$orderBody = '订单编号：'.$ordercode;
			$tade_no = $ordercode;
			$attach = $ordercode;
			$total_fee = $orderinfo['pay_money']*100;
			M('counselor_order')->where(['order_sn'=>$ordercode])->save(['pay_method'=>'wx_app']);
		}else{
			$orderinfo = $this->getOrderInfo($ordercode);
			if(!$orderinfo) {
				$this->ajaxReturn(array('s' => false, 'm' => "getorder is no"));
			}
			$orderBody = $orderinfo['orderids'];
			$tade_no = $ordercode;
			$attach = $orderinfo['title'];
			//$total_fee = 1;
			$total_fee = $orderinfo['money']*100;
			M('order')->where(['code'=>$ordercode])->save(['pay_method'=>'wx_app']);
		}
		if($this->uid==7602){
			$total_fee = 1;
		}
		$wechat = C('wechat');
		$config = [
			'mch_id'		=> $wechat['mch_id'],
			'api_key'		=> $wechat['api_key'],
			'notify_url'	=> $wechat['notify_url'],
		];
		switch ($trade_type) {
			case 'APP':
				$config['appid'] = $wechat['appid'];
				break;
			case 'MWEB':// H5支付
			case 'JSAPI':// 公众号
				$config['appid'] = $wechat['fw_app_id'];
				if($trade_type == 'JSAPI'){
					// $user = M('user')->where(['id'=>$orderinfo['user_id']])->find();
					// if(empty($user)){
					// 	$this->ajaxReturn(array('s' => false, 'm' => '用户不存在'));
					// }
					// $config['openid'] = $user['wxmopenid'];
					$config['openid'] = I('openid');
				}
				break;
			default:
				$this->ajaxReturn(array('s' => false, 'm' => '支付方式不存在'));
				break;
		}
		//$orderinfo['money']
		//P($orderBody,false);P($tade_no,false);P($total_fee,false);P($attach);
		$WxPayHelper = new \WxPayHelper($config);
		$response = $WxPayHelper->getPrePayOrder($orderBody, $tade_no, $total_fee, $attach, $trade_type);
		$data = $WxPayHelper->getOrder($response['prepay_id'], $trade_type);
		$return_data = array('s' => true, 'm' => '参数获取成功', 'trade_type'=>$trade_type, 'd' => $data, 'response'=>$response);
		$this->ajaxReturn($return_data);
	}

	/**
	 * 把数组所有元素，按照“参数=参数值”的模式用“&”字符拼接成字符串
	 * @param $para 需要拼接的数组
	 * return 拼接完成以后的字符串
	 */
	function createLinkstring($para) {
		$arg = "";
		while (list($key, $val) = each($para)) {
			$arg .= $key . "=" . $val . "&";
		}
		//去掉最后一个&字符
		$arg = substr($arg, 0, count($arg) - 2);

		//如果存在转义字符，那么去掉转义
		if (get_magic_quotes_gpc()) {$arg = stripslashes($arg);
		}

		return $arg;
	}

	/**
	 * 把数组所有元素，按照“参数=参数值”的模式用“&”字符拼接成字符串，并对字符串做urlencode编码
	 * @param $para 需要拼接的数组
	 * return 拼接完成以后的字符串
	 */
	function createLinkstringUrlencode($para) {
		$arg = "";
		while (list($key, $val) = each($para)) {
			$arg .= $key . "=" . urlencode($val) . "&";
		}
		//去掉最后一个&字符
		$arg = substr($arg, 0, count($arg) - 2);

		//如果存在转义字符，那么去掉转义
		if (get_magic_quotes_gpc()) {$arg = stripslashes($arg);
		}
		return $arg;
	}

	/**
	 * 除去数组中的空值和签名参数
	 * @param $para 签名参数组
	 * return 去掉空值与签名参数后的新签名参数组
	 */
	function paraFilter($para) {
		$para_filter = array();
		while (list($key, $val) = each($para)) {
			if ($key == "sign" || $key == "sign_type" || $val == "")
				continue;
			else
				$para_filter[$key] = $para[$key];
		}
		return $para_filter;
	}

	/**
	 * 对数组排序
	 * @param $para 排序前的数组
	 * return 排序后的数组
	 */
	function argSort($para) {
		ksort($para);
		reset($para);
		return $para;
	}

	/**
	 * RSA签名
	 * @param $data 待签名数据
	 * @param $private_key_path 商户私钥文件路径
	 * return 签名结果
	 */
	function rsaSign($data, $private_key_path) {
		$priKey = file_get_contents($private_key_path);
		$res = openssl_get_privatekey($priKey);
		openssl_sign($data, $sign, $res);
		openssl_free_key($res);
		//base64编码
		$sign = base64_encode($sign);
		return $sign;
	}

	public function getSign($parm) {
		$alipay = C('alipay');
		$privateKey = openssl_get_privatekey(file_get_contents($alipay['privateKey']));
		$data = $parm;
		$sign = '';
		openssl_sign($data, $sign, $privateKey, OPENSSL_ALGO_SHA1);
		return base64_encode($sign);
		exit();
	}

	public function ArrayToString($arr) {
		$parm = array();
		foreach ($arr as $k => $v) {
			$parm[] = $k . '="' . $v . '"';
		}
		$parms = implode('&', $parm);
		return $parms;
	}

	/**
	 * 获取返回时的签名验证结果
	 * @param $para_temp 通知返回来的参数数组
	 * @param $sign 返回的签名结果
	 * @return 签名验证结果
	 */
	function getSignVeryfy($para_temp, $sign) {
		//除去待签名参数数组中的空值和签名参数
		$para_filter = $this->paraFilter($para_temp);
		//对待签名参数数组排序
		$para_sort = $this->argSort($para_filter);
		//把数组所有元素，按照“参数=参数值”的模式用“&”字符拼接成字符串
		$alipay = C('alipay');
		$isSgin = false;
		$isSgin = $this->rsaVerify($this->createLinkstring($para_sort), trim($alipay['publicKey']), $sign);
		return $isSgin;
	}

	/**
	 * RSA验签
	 * @param $data 待签名数据
	 * @param $ali_public_key_path 支付宝的公钥文件路径
	 * @param $sign 要校对的的签名结果
	 * return 验证结果
	 */
	function rsaVerify($data, $ali_public_key_path, $sign) {
		$pubKey = file_get_contents($ali_public_key_path);
		$res = openssl_get_publickey($pubKey);
		$result = (bool)openssl_verify($data, base64_decode($sign), $res);
		openssl_free_key($res);
		return $result;
	}

	/**
	 * 获取订单数据
	 * @param undefined $ordercode
	 * @return
	 */
	function getOrderInfo($ordercode) {
		$order = M('Order')->where(array('code' => $ordercode))->find();
		if (empty($order))return false;
		return array('title' => $ordercode, 'user_id'=>$order['uid'],'money' => $order['cprice'], 'orderids' => "订单编号：" . $ordercode, );
	}

	/**
	 * 申请加盟
	 * liuzm
	 * 2016年12月16日00:08:25
	 * */
	public function apply_add() {
		$uid = $this->uid;
		$find = M('join')->where('uid="' . $uid . '"')->find();
		if (!empty($find)) {
			$this->ajaxReturn(array('s' => false, 'm' => '已经申请过'));
		}
		$name = I('name');
		$phone = I('phone');
		$adress = I('adress');
		$money = I('money');
		$data = array('uid' => $uid, 'name' => $name, 'phone' => $phone, 'adress' => $adress, 'money' => $money, 'ctime' => time(), 'status' => 1, //1未通过 2通过
		'uid' => $uid, );
		$res = M('join')->add($data);
		if (false !== $res) {
			$this->ajaxReturn(array('s' => true, 'm' => '添加成功'));
		} else {
			$this->ajaxReturn(array('s' => false, 'm' => '添加失败'));
		}
	}

	//获取订单
	public function order_type() {
		$uid = $this->uid;
		$type = I('type');
		switch ($type) {//0待付款1待发货2待收货3待评价
			case '0' :
				$where = array('uid' => $uid, 'status' => 0, 'pay_status' => 0);
				break;
			case '1' :
				$where = array('uid' => $uid, 'status' => 1, 'pay_status' => 1);
				break;
			case '2' :
				$where = array('uid' => $uid, 'status' => 2, 'wu_status' => 1);
				break;
			case '3' :
				$where = array('uid' => $uid, 'status' => 3);
				break;
			default :
				$where = array('uid' => $uid, 'status' => 0, 'pay_status' => 0);
				break;
		}
		$res = M('order')->where($where)->order('ctime desc')->select();
		$list=array();
        $time = time() - 86400*7;
		foreach ($res as $key => $value) {
			$code = $value['code'];
			$orderInfo = M("order_info")->where(array('code' => $code))->select();
			$data=array();
			foreach ($orderInfo as $k => $v) {
				$pdata = M('product')->where(array('id' => $v['pid']))->find();
				$pdata['listimg'] = json_decode($pdata['listimg']);
				$adata = M('product_attr')->where(array('id' => $v['aid']))->find();
				$data[$k]['listimg'] = $pdata['listimg'][0];
				$data[$k]['num'] = $v['num'];
				$data[$k]['title'] = $pdata['title'];
				$data[$k]['id'] = $pdata['id'];
				$data[$k]['ds'] = $pdata['ds'];
				$data[$k]['pirc'] = intval($adata['dif']) + intval($pdata['price']);
				$data[$k]['attr'] = $adata['name'];
			}
			$refund_btn = 0;
			// 物流
			$logistics = logistics_com($value['logistics_type']);
			if($logistics){
				$value['logistics_com'] = $logistics['com'];
			}else{
				$value['logistics_com'] = '';
			}
			$return = M('return')->where(['order_id'=>$value['id']])->find();
			if($value['pay_status'] == 1 && $value['status'] == 1){
				// 已付款 待发货
				if(empty($return) || $return['status'] == 3){
					$refund_btn = 1;// 售前退款按钮
				}
			}
			$value['refund_btn'] = $refund_btn;
			$return_btn = 0;
			if($value['pay_status'] == 1 && in_array($value['status'], ['2', '3', '4'])){
				// 已付款 已发货
				if(empty($return) || $return['status'] == 3){
					if(empty($value['receipt_time']) || $value['receipt_time'] > $time){
						$return_btn = 1;// 售后退货按钮
					}
				}
			}
			// 退款详情
			$return_info_btn = 0;
			if($return && in_array($return['status'], ['4', '5'])){
				$return_info_btn = 1;
			}
			// 退货填写物流
			$return_wl_btn = 0;
			if($return){
				if($return['refund_type'] == 2	&& $return['status'] == 2){
					$return_wl_btn = 1;
				}
			}
			$value['return_id'] = $return ? $return['id'] : 0;
			$value['return_status'] = $return ? $return['status'] : 0;
			$value['return_btn'] = $return_btn;
			$value['return_wl_btn'] = $return_wl_btn;
			$value['return_info_btn'] = $return_info_btn;
			$list[$key]=$value;
			$list[$key]['data'] = $data;
		}
		$this->ajaxReturn(array('s' => true, 'd' => $list));
	}

	//返回二级分类
	public function two_category() {
		$id = I('id');
		if ($id == 1) {
			$content = "麻将资讯";
		} elseif ($id == 2) {
			$content = "新闻";
		} elseif ($id == 3) {
			$content = "打牌好处";
		} elseif ($id == 4) {
			$content = "麻将历史";
		} elseif ($id == 5) {
			$content = "今天吃什么";
		} else {
			$content = "错误";
		}

		$data = array('category' => $content);
		if($content == '错误'){
			if($id){
				$data = ['id'=>$id];
			}
		}

		$list = M('category')->where($data)->find();

		$pid = $list['id'];

		try {
			$twoList = M('category')->where(array('pid' => $pid))->select();
		} catch(Exception $e) {
			$this->ajaxReturn(array('s' => false));
		}
		if ($twoList) {
			$this->ajaxReturn(array('s' => true, 'd' => $twoList));
		} else {
			$this->ajaxReturn(array('s' => true, 'd' => ''));
		}
	}

	//首页轮播图
	public function index_img() {
		$art = M('index_img');
		$res = M('index_img')->order('sort desc')->select();
		$list = array();
		foreach ($res as $key => $value) {
			$value['img'] = json_decode($value['img'], true);
			$value['img'] = $value['img'][0];
			$list[] = $value;
		}

		if ($res) {
			$this->ajaxReturn(array('s' => true, 'd' => $list));
		} else {
			$this->ajaxReturn(array('s' => false));
		}
	}

	public function index_img_detail(){
		$id = I('id');
		$info = M('index_img')->where(['id'=>$id])->field('title,content')->find();
		if($info){
			$this->ajaxReturn(array('s' => true, 'd' => $info));
		}else{
			$this->ajaxReturn(array('s' => false));
		}
	}

	//验证第三方信息
	public function v_login() {

		$data = I('post.');
		//$data = json_decode($data); 

		switch ($data['id']) {
			case 'weixin' :
				$where['wxopenid'] = $data['openid'];
				break;
			case 'qq' :
				$where['qqopenid'] = $data['openid'];
				break;
			default :
				$this->ajaxReturn(array('s' => false, 'm' => '参数错误'));
				break;
		}
		try {
			$res = M('user')->where($where)->find();
		} catch(Exception $e) {
			$this->ajaxReturn(array('s' => false, 'm' => '参数错误'));
		}
		if (!empty($res)) {
			$res_save = M('user')->where($where)->save(array('cid'=>$data['cid'],'eqsb'=>$data['eqsb']));
			$token = M('token')->where(array('uid' => $res['id']))->find();
			$db = array('token' => $token['token'], 'phone' => $res['phone']);
			$this->ajaxReturn(array('s' =>true,'d' =>$db));
		} else {
			$this->ajaxReturn(array('s' =>true,'d' => "new"));
		}

	}
	//商品评论
	public function product_ping() {
		$userdata =$_POST;
		$lydata=$userdata['lydata'];
		$code=$userdata['order_id'];
		foreach ($lydata as $key => $value) {
		  $con =$value['content'];
		  $img = $this->uploadimgtow($value['images']);
		  $id=$value['pro_id'];
		  $data = array( 'content' =>base64_encode($con), 'p_id' => $id, 'ctime' => time(), 'img' => json_encode($img), 'uid' => $this->uid, );
		  $res = M('product_reply')->add($data);
		  $list = M('product')->find($id);
		  $num_p = $list['pinglun'] + 1;
		  $res_save = M('product')->where(array('id' => $id))->data(array('pinglun' => $num_p))->save();
		}
		$ME=M('order')->where(array('code'=>$code))->save(array('status'=>4));
		//然后评论数加一
		if (false !== $res && false !== $list && false !== $res_save) {
			$this->ajaxReturn(array('s' => true));
		} else {
			$this->ajaxReturn(array('s' => false));
		}
	}

	//店铺搜索
	public function keywode_shop() {
		$lng = I('lng');
		//经度
		$lat = I('lat');
		//纬度
		$key=I('shopname');
		$where['shopname'] = array("like","%".$key."%");
		$where['status'] = '1';
		$list = M('shop')->where($where)->select();
		foreach ($list as $k => $v) {
			$list_p = M("shop_reply")->where('s_id="' .$v['id'] . '"')->select();
			$p_num = count($list_p);
			foreach ($list_p as $key => $value) {
					$xing = $xing + $value['xing'];
				}
			$arr[$k]['xing']= ceil($xing / $p_num);
			$order_num = M('appointment')->where('shopid="' .$v['id']. '"')->count();
		
			$arr[$k]['order_num'] = count($list_p) + $order_num;
			$arr[$k]['shopname'] =$v['shopname'];
			$arr[$k]['area']=$v['area'];
			$arr[$k]['lng']=$v['lng'];
			$arr[$k]['lat']=$v['lat'];
			$arr[$k]['id']=$v['id'];
			$arr[$k]['listimg']=$v['listimg'];
			
			$val = ($v['lng'] - $lng) * ($v['lng'] - $lng) + ($v['lat'] - $lat) * ($v['lat'] - $lat);
			$arr[$k]['ju'] = round(sqrt($val), 5);
		}
		$arr = $this->array_sort($arr, 'ju');
		$returndata = array();
		foreach ($arr as $re) {
			$returndata[] = $re;
		}
		if (false !== $list) {
			$this->ajaxReturn(array('s' => true, 'd' => $returndata));
		} else {
			$this->ajaxReturn(array('s' => false));
		}
	}

	//商城轮播图
	public function shop_index() {
		$art = M('shop_img');
		$res = M('shop_img')->select();
		$list = array();
		foreach ($res as $key => $value) {
			$value['img'] = json_decode($value['img'], true);
			$value['img'] = $value['img'][0];
			$list[] = $value;
		}
		$data=array();
		$data['img']=$list;
		$resad = M('product_advertising')->order('id desc')->find();
		$resad['img'] = json_decode($resad['img'], true);
		$data['advertising']= $resad;
		$zzh=array();
		$resca = M('product_category')->where(['status'=>1])->order('sort desc')->select();
		foreach ($resca as $key => $value) {
			$value['cate_img'] = json_decode($value['cate_img'], true);
			$value['cate_img'] = $value['cate_img'][0];
			$zzh[] = $value;
		}
		$data['category']=$zzh;
		$pa=array();
		$rest = M('product')->order('sales desc')->limit(6)->select();
		foreach ($rest as $k => $v) {
			$panm=array();
			$panm['id']=$v['id'];
			$panm['listimg']=json_decode($v['listimg'], true);
			$panm['listimg'] =$panm['listimg'][0];
			$panm['title']=$v['title'];
			$panm['sales']=$v['sales'];
			$panm['price']=$v['price'];
			$pn[]=$panm;	
		}
		$data['hot']=$pn;
		//P($data);
		if ($res) {
			$this->ajaxReturn(array('s' => true, 'd' => $data));
		} else {
			$this->ajaxReturn(array('s' => false));
		}
	}
	//广告位
	public function product_advertising() {
		if ($res) {
			$this->ajaxReturn(array('s' => true, 'd' => $list));
		} else {
			$this->ajaxReturn(array('s' => false));
		}
	}

	/*
	 * liuzm
	 * 2017年1月17日17:00:18
	 * 版本控制
	*/
	public function version(){
		$system =	I('system');//系统
		$version=	I('version');//版本
		$list	=	M('version')->where('system="'.$system.'"')->order('id desc')->find();
		if(compareVersion($version, $list['version']) < 0){
			$this->ajaxReturn(array('s' => true, 'd' => $list['url'],'m'=>$list['content']));
		}else{
			$this->ajaxReturn(array('s' => false));
		}
	}

	/**
	 * 获取娱头条
	 * @author 张亚伟 <zhangyw@zhijin101.com>
	 * @return void
	 */
	public function headline(){
		$list = M('article')->where(['cid'=>86])->order('ctime desc')->field('id,title')->limit(3)->select();
		if (false !== $list) {
			$this->ajaxReturn(['s' => true, 'd' => $list]);
		} else {
			$this->ajaxReturn(['s' => false]);
		}
	}

	/**
	 * 获取直播列表
	 * @author 张亚伟 <zhangyw@zhijin101.com>
	 * @return void
	 */
	public function live_list(){
		$page = I('page/d', 0);
		$model = M('live_video');
		$map = ['is_show'=>1];
		if($page){
			$list = $model->where($map)->order('sort asc,id desc')->page($page, 20)->field('id,title,cover,number,status,url')->select();
		}else{
			$list = $model->where($map)->order('sort asc,id desc')->field('id,title,cover,number,status,url')->select();
		}
		foreach($list as $key=>&$row){
			$row['cover'] = json_decode($row['cover'], true);
			$row['cover'] = isset($row['cover']['0']) ? $row['cover'][0]:'';
			$row['status'] = $row['status'] ? '直播中' : '暂不在播';
		}
		if($list !==false){
			$this->ajaxReturn(['s'=>true, 'd'=>$list]);
		}else{
			$this->ajaxReturn(['s'=>false]);
		}
	}

	/**
	 * 维修工申请
	 * @author 张亚伟 <zhangyw@zhijin101.com>
	 * @return void
	 */
	public function maintainer_apply(){
		$model = M('maintainer');
		if($model->where(['uid'=>$this->uid])->find()){
			$this->ajaxReturn(['s' => false, 'm' => '不能重复申请']);
		}
		$data = I('post.');
		$data['uid'] = $this->uid;
		$data['img'] = $this->uploadimgsy('img');
		$data['img'] = !empty($data['img']) ? explode(',', $data['img'])[0] : '';
		$data['check_status'] = 0;
		$data['status'] = 0;
		$data['create_time'] = time();
		
		$id = $model->add($data);
		if($id){
			$this->ajaxReturn(['s'=>true, 'm'=>'申请成功']);
		}else{
			$this->ajaxReturn(['s'=>false, 'm'=>'申请失败']);
		}
	}

	/**
	 * 获取维修工信息
	 * @author 张亚伟 <zhangyw@zhijin101.com>
	 * @return void
	 */
	public function maintainer_info(){
		$id = I('id');
		$info =  M('maintainer')->where(['id'=>$id, 'status'=>1])->field("id,img,name,assessment,score,comment_num,district,lng,lat,address,mobile,views,like_num,ad_id")->find();
		if($info){
			if($info['ad_id']){
				$ad = M('article_advertising')->where(['id'=>$info['ad_id']])->find();
			}
			M('maintainer')->where(['id'=>$id])->setInc('views', 1);
			$info['score'] = round($info['score']);
			$list = get_comment('maintainer', $id, 0);
			$info['comments'] = $list;
			$result = ['s'=>true, 'd'=>$info];
			if(!empty($ad)){
				$result['ad'] = $ad;
			}
			$this->ajaxReturn($result);
		}else{
			$this->ajaxReturn(['s'=>false]);
		}
	}

	public function maintainer_category(){
		$category = yzl_config('wxg.wxg_category');
		if($this->system == 'ios'){
			unset($category[1]);
		}
		$this->ajaxReturn(['s'=>true, 'category'=>$category]);
	}

	/**
	 * 获取维修工信息
	 * @author 张亚伟 <zhangyw@zhijin101.com>
	 * @return void
	 */
	public function maintainer_list(){
		$keyword = I('keyword');
		$type = I('type');
		$lat = I('lat/f', 0);
		$lng = I('lng/f', 0);
		$page = I('page/d', 0);
		$category_id = I('category_id');
		$district = I('district');
		$map['check_status'] = 1;
		$map['status'] = 1;
		$map['district'] = $district;
		if($keyword){
			$map['name'] = ['like', '%'.$keyword.'%'];
		}
		if($category_id){
			$map['category_id'] = $category_id;
		}
		// if(empty($lng) || empty($lat)){
		// 	$this->ajaxReturn(['s'=>false, 'm'=>'参数错误']);
		// }
		$list = [];
		$model = M('maintainer');
		$field = 'id,name,score,img,mobile,district,getDistance('.$lng.','.$lat.',lng,lat) as distance';
		$order = '';
		switch($type){
			case 2:// 人气
				// 评价数量排序
				$order = 'comment_num desc';
				break;
			case 3:// 评价
				$order = 'score desc';
				break;
			case 4:// 综合
				$field.=",comment_num*score as total_score";
				$order = 'total_score desc';
				break;
			case 1:// 距离
			default:
				$order = 'distance asc';
				break;
		}
		if($page){
			$list = $model->where($map)->field($field)->order($order)->page($page, 20)->select();
		}else{
			$list = $model->where($map)->field($field)->order($order)->select();
		}
		if($list){
			foreach($list as $key=>&$row){
				$row['distance'] = distance_txt($row['distance']);
				$row['score'] = round($row['score']);
			}
		}
		if($list !== false){
			$this->ajaxReturn(['s'=>true, 'd'=>$list]);
		}else{
			$this->ajaxReturn(['s'=>false]);
		}
	}

	/**
	 * 添加评价
	 * @author 张亚伟 <zhangyw@zhijin101.com>
	 * @return void
	 */
	public function add_comment(){
		$target_id = I('id');
		$type = I('type');
		$score = I('score/d', 0);
		$content = I('content');
		$target_model;
		switch($type){
			case 'maintainer':// 维修工
				$target_model = M('maintainer');
				$info = $target_model->where(['id'=>$target_id])->find();
				if(empty($info)){
					$this->ajaxReturn(['s'=>false, 'm'=>'维修工不存在']);
				}
				break;
		}
		$uid = $this->uid;
		$imgs = $this->uploadimgsy('imgs');
		$data = [
			'type'			=> $type,
			'uid'			=> $this->uid,
			'target_id'		=> $target_id,
			'imgs'			=> $imgs,
			'score'			=> $score,
			'content'		=> $content,
			'is_show'		=> 1,
			'create_time'	=> time()
		];
		$model = M('comment');
		M()->startTrans();
		$id = $model->add($data);
		if(!$id){
			M()->rollback();
			$this->ajaxReturn(['s'=>false, 'm'=>'失败']);
		}

		$comment = $model->where(['type'=>$type, 'target_id' =>$target_id])->field('sum(score) as score,count(*) as num')->find();
		$comment['score'] = $comment['score'] ?:0;
		$target_score = $comment['num'] ? $comment['score']/$comment['num'] : 0;
		$update = [
			'score' 		=> round($target_score, 1),
			'comment_num' 	=> $comment['num'],
		];
		$res = $target_model->where(['id'=>$target_id])->save($update);

		if ($res !== false) {
			M()->commit();
			$this->ajaxReturn(['s'=>true]);
		} else {
			M()->rollback();
			$this->ajaxReturn(['s'=>false, 'm'=>'失败']);
		}
	}

	/**
	 * 获取评论
	 * @author 张亚伟 <zhangyw@zhijin101.com>
	 * @return void
	 */
	public function get_comment(){
		$id = I('id');
		$type = I('type');
		$page = I('page/d', 0);
		$num = I('num/d', 20);
		$list = get_comment($type, $id, $page, $num);
		if($list !== false){
			$this->ajaxReturn(['s'=>true, 'd'=>$list]);
		}else{
			$this->ajaxReturn(['s'=>false]);
		}
	}

	/**
	 * 品牌申请
	 * @author 张亚伟 <zhangyw@zhijin101.com>
	 * @return void
	 */
	public function brand_apply(){
		$data = I('post.');
		$data['uid'] = $this->uid;
		$data['logo'] = $this->uploadimgsy('logo');
		$data['logo'] = !empty($data['logo']) ? explode(',', $data['logo'])[0] : '';
		// $data['imgs'] = $this->uploadimgsy('imgs');
		$data['status'] = 0;
		$data['check_status'] = 0;
		$data['create_time'] = time();
		$id = M('brand')->add($data);
		if($id){
			$this->ajaxReturn(['s'=>true, 'm'=>'申请成功']);
		}else{
			$this->ajaxReturn(['s'=>false, 'm'=>'申请失败']);
		}
	}

	/**
	 * 获取首页品牌
	 * @author 张亚伟 <zhangyw@zhijin101.com>
	 * @return void
	 */
	public function home_brand(){
		$list = M('brand')->where(['status'=>1, 'check_status'=>1])->field('id,logo,brand_name')->order('is_top desc,thumbs_up desc,sort asc')->limit(5)->select();
		if($list){
			$num = 5-count($list);
			if($num > 0){
				$arr = M('brand')->where(['status'=>1, 'check_status'=>1])->field('id,logo,brand_name')->order('is_top desc,thumbs_up desc,sort asc')->limit($num)->select();
				if($arr){
					$list = array_merge($list, $arr);
				}
			}
		}
		if($list !== false){
			$this->ajaxReturn(['s'=>true, 'd'=>$list]);
		}else{
			$this->ajaxReturn(['s'=>false]);
		}
	}

	/**
	 * 获取品牌
	 * @author 张亚伟 <zhangyw@zhijin101.com>
	 * @return void
	 */
	public function brand_page(){
		$list = M('brand')->where(['status'=>1, 'check_status'=>1])->field('id,brand_name,logo')->order('is_top desc,thumbs_up desc,sort asc')->select();
		if($list !== false){
			$top_img = M('slider')->where(['type'=>1])->order('id asc')->field('img,link')->find();
			$this->ajaxReturn(['s'=>true, 'd'=>['list'=>$list, 'top_img'=>$top_img]]);
		}else{
			$this->ajaxReturn(['s'=>false]);
		}
	}

	/**
	 * 获取品牌详情消息
	 * @author 张亚伟 <zhangyw@zhijin101.com>
	 * @return void
	 */	
	public function brand_detail()
	{
		$id = I('id');
		$brand = M('brand')->where(['id'=>$id])->field('id,brand_name,logo,hotline,brand_desc,product_name,imgs,views,thumbs_up,content,ad_id')->find();
		if($brand){
			M('brand')->where(['id'=>$id])->setInc('views', 1);
			$brand['is_thumbs_up'] = 0;
			if($this->uid){
				$today_start = mktime(0, 0, 0, date('m'), date('d'), date('Y'));
				$today_end = mktime(23, 59, 59, date('m'), date('d'), date('Y'));
				$map = [
					'uid' => $this->uid,
					'brand_id' => $id,
					'create_time&create_time' => [['egt', $today_star], ['elt', $today_end], '_multi'=>true],
				];
				$log = M('brand_thumbs_up')->where($map)->find();
				if(!empty($log)){
					$brand['is_thumbs_up'] = 1;
				}
			}
			if($brand['ad_id']){
				$ad = M('article_advertising')->where(['id'=>$brand['ad_id']])->find();
			}
			$brand['imgs'] = !empty($brand['imgs']) ? explode(',', $brand['imgs']) : [];
			// $goods_list = M('nearby_shop_goods')->where(['brand_id'=>$id])->field('id,goods_name,picture')->limit(6)->select();
			// $brand['goods_list'] = $goods_list;
			$result = ['s'=>true, 'd'=>$brand];
			if(!empty($ad)){
				$result['ad'] = $ad;
			}
			$this->ajaxReturn($result);
		}else{
			$this->ajaxReturn(['s'=>false]);
		}
	}


	/**
	 * 点赞
	 * @author 张亚伟 <zhangyw@zhijin101.com>
	 * @return void
	 */	
	public function thumbs_up()
	{
		$id = I('id/d', 0);
		$brand_model = M('brand');
		$brand = $brand_model->where(['id'=>$id])->find();
		if(empty($brand)){
			$this->ajaxReturn(['s'=>false, 'm'=>'品牌不存在']);
		}
		$today_start = mktime(0, 0, 0, date('m'), date('d'), date('Y'));
		$today_end = mktime(23, 59, 59, date('m'), date('d'), date('Y'));
		$map = [
			'uid' => $this->uid,
			'create_time&create_time' => [['egt', $today_start], ['elt', $today_end], '_multi'=>true],
		];
		$thumbs_up_model = M('brand_thumbs_up');
		$log = $thumbs_up_model->where($map)->find();
		if(!empty($log)){
			$this->ajaxReturn(['s'=>false, 'm'=>'今天已点赞']);
		}
		$data = [
			'uid' => $this->uid,
			'brand_id' => $id,
			'create_time' => time(),
		];
		M()->startTrans();
		$thumbs_up_id = $thumbs_up_model->add($data);
		if(!$thumbs_up_id){
			M()->rollback();
			$this->ajaxReturn(['s'=>false, 'm'=>'点赞失败']);
		}
		$res = $brand_model->where(['id'=>$id])->setInc('thumbs_up', 1);
		if($res !== false){
			M()->commit();
			$this->ajaxReturn(['s'=>true, 'm'=>'点赞成功', 'd'=>['thumbs_up'=>($brand['thumbs_up'] + 1)]]);
		}
		M()->rollback();
		$this->ajaxReturn(['s'=>false, 'm'=>'点赞失败']);
	}

	/**
	 * 申请免费打牌
	 * @author 张亚伟 <zhangyw@zhijin101.com>
	 * @return void
	 */
	function apply_free_play_mj(){
		$data = I('post.');
		if(empty($data['card_room'])){
			$this->ajaxReturn(['s'=>false, 'm'=>'请输入店铺名称']);
		}else{
			if(empty($data['mobile'])){
				$this->ajaxReturn(['s'=>false, 'm'=>'请输入电话']);
			}
			$shop_info = M('shop')
			// ->where(['shopname'=>$data['card_room'], 'tel'=>$data['mobile'], 'status'=>1])
        	->where(['shopname|phone|tel'=>[$data['card_room'], $data['mobile'], $data['mobile'], '_multi'=>true], 'status'=>1])
			->find();
			if(empty($shop_info)){
				$this->ajaxReturn(['s'=>false, 'm'=>'棋牌室还没有入驻，请先入驻棋牌室。']);
			}else{
				$data['shop_id'] = $shop_info['id'];
			}
		}
		$data['uid'] = $this->uid;
		$data['status'] = 0;
		$data['free_date'] = !empty($data['free_date']) ? strtotime($data['free_date']) : 0;
		$data['business_license'] = $this->uploadimgsy('business_license');
		$data['check_status'] = 0;
		$data['create_time'] = time();
		$id = M('free_play')->add($data);
		if($id){
			$this->ajaxReturn(['s'=>true, 'm'=>'申请成功']);
		}else{
			$this->ajaxReturn(['s'=>false, 'm'=>'申请失败']);
		}
	}

	/**
	 * 免费打牌列表
	 * @author 张亚伟 <zhangyw@zhijin101.com>
	 * @return void
	 */
	public function free_play_mj(){
		$keyword = I('keyword');
		$type = I('type');
		$lat = I('lat/f', 0);
		$lng = I('lng/f', 0);
		$page = I('page/d', 0);
		$pro = I('pro');
		$city = I('city');
		$area = I('area');
		
		if($pro){
			$map['s.pro'] = $pro;
		}
		if($city){
			$map['s.city'] = $city;
		}
		$map['s.area'] = $area;
		$map['f.check_status'] = 1;
		$map['f.status'] = 1;
		if($keyword){
			$map['s.shopname'] = ['like', '%'.$keyword.'%'];
		}
		$day_time = strtotime(date('Y-m-d'));
		$map['f.free_date'] = ['egt', $day_time];
		$list = [];
		$model = M('free_play');
		$field = 'f.shop_id,f.free_date,s.shopname,s.listimg,s.area,getDistance('.$lng.','.$lat.',s.lng,s.lat) as distance,count(sr.id) as p_num,sum(sr.xing) as xing';
		$order = '';
		switch($type){
			case 2:// 人气
				$order = 's.renqi desc';
				break;
			case 3:// 评价
				$order = 's.pinglun desc';
				break;
			case 4:// 综合
				$order = 'f.id asc';
				break;
			case 1:// 距离
			default:
				$order = 'distance asc';
				break;
		}
		if($page){
			$list = $model->alias('f')
					->join('left join __SHOP__ s on  f.shop_id=s.id')
					->join('left join __SHOP_REPLY__ sr on f.shop_id=sr.s_id')
					->where($map)->field($field)->order($order)->group('f.id')->page($page, 20)->select();
		}else{
			$list = $model->alias('f')
					->join('left join __SHOP__ s on  f.shop_id=s.id')
					->join('left join __SHOP_REPLY__ sr on f.shop_id=sr.s_id')
					->where($map)->field($field)->order($order)->group('f.id')->select();
		}
		if($list){
			$curremt_year = date('Y.');
			foreach($list as $key=>&$row){
				$row['distance'] = distance_txt($row['distance']);
				$row['xing'] = $row['xing'] ? $row['xing'] : 0;
				$row['score'] = $row['p_num'] ? ceil($row['xing'] / $row['p_num']) : 0;
				$order_num = M('appointment')->where(['shopid'=>$row['shop_id']])->count();
				$row['order_num'] = $row['p_num'] + $order_num;
				$row['free_date'] = date('Y.m.d', $row['free_date']);
				$row['free_date'] = str_replace($curremt_year, '', $row['free_date']);
				unset($row['xing']);
				unset($row['p_num']);
			}

			$amap_key = 'd7cdde040024dc1fe22157970ba6bd6b';
			$origins = '';
            foreach ($list as $key => $row) {
                $origins.= ($origins ? "|":'').$row['lng'].','.$row['lat'];
            }

            $url = "http://restapi.amap.com/v3/assistant/coordinate/convert?key={$amap_key}&locations={$origins}&coordsys=baidu";
            $res = curl_get($url);
            $res = json_decode($res, true);

            $origins = '';
            if($res['status'] == '1'){
            	$locations = $res['locations'];
            	$arr = explode(';', $locations);
            	foreach ($arr as $key => $row) {
            		$origins.= ($origins ? "|":'').explode(',', $row)[0].','.explode(',', $row)[1];
            	}
            }
			$url = "http://restapi.amap.com/v3/assistant/coordinate/convert?key={$amap_key}&locations={$lng},{$lat}&coordsys=gps";
            $res = curl_get($url);
            $res = json_decode($res, true);      
			// dump($res);      
            if($res['status'] == '1'){
            	$lng = explode(',', $res['locations'])[0];
            	$lat = explode(',', $res['locations'])[1];
            }
            try{
                require_once 'ThinkPHP/Library/Vendor/autoload.php';
                $res = \yishuixm\lbs\LbsAmap::distance($amap_key, $origins, $lng.','.$lat, 1);
                $res = json_decode($res, true);
                if($res['status'] == 1){
                    foreach ($list as $key => &$row) {
                        $row['distance'] = $res['results'][$key]['distance'];
                    }
                    if(empty($type) || $type == '1'){
                    	array_multisort(array_column($list, 'distance'), SORT_ASC, $list);	
                    }
                }
            }catch(\Exception $e){

            }			


			if($type == 4){
				$list = $this->array_sort($list, 'score', 'desc');
			}
		}
		if($list !== false){
			$this->ajaxReturn(['s'=>true, 'd'=>$list]);
		}else{
			$this->ajaxReturn(['s'=>false]);
		}
	}

	/**
	 * 附近麻将机店申请
	 * @author 张亚伟 <zhangyw@zhijin101.com>
	 * @return void
	 */
	public function nearby_shop_apply()
	{
		$model = M('nearby_shop');
		if($model->where(['uid'=>$this->uid])->find()){
			
			$this->ajaxReturn(['s' => false, 'm' => '已经申请过']);
		}

		$data = I('post.');
		$data['picture'] = $this->uploadimgsy('picture');
		$data['picture'] = !empty($data['picture']) ? explode(',', $data['picture'])[0] : '';
		$data['desc_img'] = $this->uploadimgsy('desc_img');
		$data['desc_img'] = !empty($data['desc_img']) ? explode(',', $data['desc_img'])[0] : '';
		$data['pictures'] = $this->uploadimgsy('pictures');
		$data['boss_img'] = $this->uploadimgsy('boss_img');
		$data['business_license'] = $this->uploadimgsy('business_license');
		$data['uid'] = $this->uid;
		$data['status'] = 0;
		$data['listing_time'] = !empty($data['listing_time']) ? strtotime($data['listing_time']) : 0;
		$data['check_status'] = 0;
		$data['create_time'] = time();
		$id = $model->add($data);
		if($id){
			$this->ajaxReturn(['s'=>true, 'm'=>'申请成功']);
		}else{
			$this->ajaxReturn(['s'=>false, 'm'=>'申请失败']);
		}
	}

	/**
	 * 首页附近麻将机店
	 * @author 张亚伟 <zhangyw@zhijin101.com>
	 * @return void
	 */
	public function home_nearby_shop()
	{
		$keyword = I('keyword');
		$lat = I('lat/f', 0);
		$lng = I('lng/f', 0);
		$page = I('page/d', 0);
		$province = I('pro');
		$city = I('city');
		$district = I('district');
		$map = [];
		if($province && $province!='false'){
			$map['province'] = $province;
		}
		if($city){
			$map['city'] = $city;
		}
		$map['district'] = $district;
		$map['check_status'] = 1;
		$map['status'] = 1;
		if($keyword){
			// $map['shop_name'] = ['like', "%".$keyword.'%'];
		}
		$model = M('nearby_shop');
		$list = $model->where($map)->field('id,shop_name,picture,member_grade,member_expire,is_auth,district,getDistance('.$lng.','.$lat.',lng,lat) as distance,lng,lat')->order('distance asc')->select();

        $amap_key = 'd7cdde040024dc1fe22157970ba6bd6b';
		if($list){

            $origins = '';
            foreach ($list as $key => $row) {
                $origins.= ($origins ? "|":'').$row['lng'].','.$row['lat'];
            }

            $url = "http://restapi.amap.com/v3/assistant/coordinate/convert?key={$amap_key}&locations={$origins}&coordsys=baidu";
            $res = curl_get($url);
            $res = json_decode($res, true);

            $origins = '';
            if($res['status'] == '1'){
            	$locations = $res['locations'];
            	$arr = explode(';', $locations);
            	foreach ($arr as $key => $row) {
            		$origins.= ($origins ? "|":'').explode(',', $row)[0].','.explode(',', $row)[1];
            	}
            }
			$url = "http://restapi.amap.com/v3/assistant/coordinate/convert?key={$amap_key}&locations={$lng},{$lat}&coordsys=gps";
            $res = curl_get($url);
            $res = json_decode($res, true);      
			// dump($res);      
            if($res['status'] == '1'){
            	$lng = explode(',', $res['locations'])[0];
            	$lat = explode(',', $res['locations'])[1];
            }
            try{
                require_once 'ThinkPHP/Library/Vendor/autoload.php';
                $res = \yishuixm\lbs\LbsAmap::distance($amap_key, $origins, $lng.','.$lat, 1);
                $res = json_decode($res, true);
                if($res['status'] == 1){
                    foreach ($list as $key => &$row) {
                        $row['distance'] = $res['results'][$key]['distance'];
                    }
                    array_multisort(array_column($list, 'distance'), SORT_ASC, $list);
                }
            }catch(\Exception $e){

            }
            
			foreach($list as $key=>&$row){
				$row['distance'] = distance_txt($row['distance']);
				$row['is_auth'] = jc_member_check($row) ? 1 : 0;
				unset($row['member_grade']);
				unset($row['member_expire']);
			}
		}
		if($list !== false){
			$this->ajaxReturn(['s'=>true, 'd'=>$list]);
		}else{
			$this->ajaxReturn(['s'=>false]);
		}
	}

	/**
	 * 附近麻将机店详情数据
	 * @author 张亚伟 <zhangyw@zhijin101.com>
	 * @return void
	 */
	public function nearby_shop_detail()
	{
		$id = I('id');
		$info = M('nearby_shop')->where(['id'=>$id])->field('id,uid,shop_name,member_grade,member_expire,picture,mobile,address,brand_name,desc_img,pictures,color,is_auth,listing_time')->find();
		if($info){
			$info['listing_time'] = date('Y-m-d', $info['listing_time']);
			$info['pictures'] = explode(',', $info['pictures']);
			$goods_list = M('nearby_shop_goods')->where(['nearby_shop_id'=>$id, 'is_on_sale'=>1])->field('id,goods_name,price,picture')->order('sort asc')->select();
			$info['goods_list'] = $goods_list;
			$info['is_self'] = 1;
			$info['is_member'] = jc_member_check($info) ? 1 : 0;
			$info['is_auth'] = $info['is_member'];
			$user_phone = '';
			if($info['uid']){
				$user = M('user')->where(['id'=>$info['uid']])->find();
				if($user){
					$user_phone = $user['phone'];
				}
			}
			$info['user_phone'] = $user_phone;
			unset($info['member_expire']);
			unset($info['member_grade']);
			unset($info['uid']);
			$this->ajaxReturn(['s'=>true, 'd'=>$info]);
		}else{
			$this->ajaxReturn(['s'=>false]);
		}
	}
	
	/**
	 * 获取经销商商品信息
	 * @author 张亚伟 <zhangyw@zhijin101.com>
	 * @return void
	 */
	public function nearby_shop_goods()
	{
		$id = I('id');
		$info = M('nearby_shop_goods')->where(['id'=>$id])->field('nearby_shop_id,content,alipay_qr,wechat_pay_qr,views,like_num,ad_id')->find();
		if($info){
			if($info['ad_id']){
				$ad = M('article_advertising')->where(['id'=>$info['ad_id']])->find();
			}
			M('nearby_shop_goods')->where(['id'=>$id])->setInc('views', 1);
			$shop = M('nearby_shop')->where(['id'=>$info['nearby_shop_id']])->find();
			$result = ['s'=>true, 'd'=>$info, 'mobile'=>$shop ? $shop['mobile'] : ''];
			if($ad){
				$result['ad'] =$ad;
			}
			$this->ajaxReturn($result);
		}else{
			$this->ajaxReturn(['s'=>false]);
		}
	}

	/**
	 * 获取首页广告
	 * @author 张亚伟 <zhangyw@zhijin101.com>
	 * @return void
	 */
	public function home_ad()
	{
		$list = M('ad')->where(['type'=>1])->order('id asc')->field('name,img,link')->select();
		if($list !== false){
			$this->ajaxReturn(['s'=>true, 'd'=>$list]);
		}else{
			$this->ajaxReturn(['s'=>false]);
		}
	}

	public function app_css()
	{
		$this->ajaxReturn(['s'=>true, 'd'=>[
				'http://www.yuzhuli.com/Public/app/css/NewStyle.css',
				'http://www.yuzhuli.com/Public/app/css/public.css',
				'http://www.yuzhuli.com/Public/app/css/style.css',
			]
		]);
	}


	/**
	 * 获取签到商品
	 * @return [type] [description]
	 */
	public function sign_in_prizes()
	{
		$goods = M('prizes')->order('sort asc')->field('id,title,sign_in_num,list_img')->select();
		if($goods !== false){
			$record = M('winning')->alias('w')
					  ->join('__USER__ u ON w.user_id=u.id', 'left')
					  ->join('__PRIZES__ p ON w.prizes_id=p.id', 'left')
					  ->field('u.nickname,p.title')
					  ->order('w.id desc')
					  ->limit(9)
					  ->select();
			$this->ajaxReturn(['s'=>true, 'd'=>['goods_list'=>$goods, 'record'=>$record]]);
		}else{
			$this->ajaxReturn(['s'=>false]);
		}
	}

	/**
	 * 获取商品详情
	 * @return [type] [description]
	 */
	public function prizes_detail()
	{
		$id = I('id');
		$info = M('prizes')->where(['id'=>$id])->field('id,title,share_title,share_desc,sign_in_num,list_img,img,content,views,like_num')->find();
		if($info){
			M('prizes')->where(['id'=>$id])->setInc('views', 1);
			$info['is_sign_in'] = 1;
			if($this->uid){
				$now_date_time = mktime(0, 0, 0, date('m'), date('d'), date('Y'));
				$log = M('sign_in_log')->where(['user_id'=>$this->uid])->order('id desc')->find();
				if($log && ($now_date_time <= $log['create_time'])){
					$info['is_sign_in'] = 0;
				}
			}
			//今天是否分享
			$is_share = M('share_log')->where(['scene'=>'qd', 'relation_id'=>$id, 'user_id'=>$this->uid, 'create_time'=>['between', today()]])->find() ? 1 : 0;

			$num = M('sign_in_log')->where(['user_id'=>$this->uid, 'prizes_id'=>$id])->sum('num');
			$num = $num ? $num : 0;

			$ad = M('ad')->where(['type'=>2])->order('id asc')->field('name,img,link')->find();

			$this->ajaxReturn(['s'=>true, 'd'=>['info'=>$info, 'is_share'=>$is_share, 'user_id'=>$this->uid, 'ad'=>$ad, 'num'=>$num]]);
		}else{
			$this->ajaxReturn(['s'=>false]);
		}
	}

	/**
	 * 签到成功后分享出去的页面浏览数据接口
	 */
	public function prizes_share_info()
	{
		$user_id = I('user_id');
		$id = I('id');
		$user = M('user')->where(['id'=>$user_id])->field('nickname,img')->find();
		if(empty($user)){
			$this->ajaxReturn(['s'=>false, 'msg'=>'用户不存在']);
		}
		$prizes = M('prizes')->where(['id'=>$id])->field('id,title,list_img,original_price')->find();
		if(empty($prizes)){
			$this->ajaxReturn(['s'=>false, 'msg'=>'奖品不存在']);
		}
		$winning_num = M('winning')->where(['prizes_id'=>$id])->count();

		$this->ajaxReturn(['s'=>true, 'user'=>$user, 'prizes'=>$prizes, 'winning_num'=>$winning_num]);
	}

	/**
	 * 签到
	 * @return [type] [description]
	 */
	public function prizes_sign_in()
	{
		$prizes_id = I('id');
		$type = I('type');
		$user_id = I('user_id');

		if(!in_array($type, ['1', '2'])){
			$this->ajaxReturn(['s'=>false, 'm'=>'类型错误']);
		}
		$info = M('prizes')->where(['id'=>$prizes_id])->field('id,title,sign_in_num,img,content')->find();
		if(empty($info)){
			$this->ajaxReturn(['s'=>false, 'm'=>'奖品不存在']);
		}

		$now_date_time = mktime(0, 0, 0, date('m'), date('d'), date('Y'));
		$now_time = time();
		if($type == 2){
			$token = M('token')->where(['token'=>$user_id])->find();
			if($token){
				$user_id = $token['uid'];
			}else{
				$this->ajaxReturn(['s'=>false, 'm'=>'错误']);
			}
		}
		$sign_in_num = 1;
		$data = [
			'user_id'		=> ($type == 1 ? $this->uid : $user_id),
			'type'			=> $type,
			'help_user_id'	=> ($type == 1 ? 0 : $this->uid),
			'prizes_id'		=> $prizes_id,
			'create_time'	=> $now_time,
		];

		if(M('winning')->where(['user_id'=>$data['user_id'], 'prizes_id'=>$prizes_id])->find()){
			$this->ajaxReturn(['s'=>false, 'm'=>'您已中奖']);
		}

		$num = M('sign_in_log')->where(['user_id'=>$data['user_id'], 'prizes_id'=>$prizes_id])->sum('num');
		$num = $num ? $num : 0;
		switch ($type) {
			case '1'://自己签到
				$log = M('sign_in_log')->where(['user_id'=>$this->uid])->order('id desc')->find();
				if($log){
					if($now_date_time <= $log['create_time']){
						$this->ajaxReturn(['s'=>false, 'm'=>'今天已签到']);
					}
				}
				$sign_in_num = 2;
				break;
			case '2':// 帮签到
				$log = M('sign_in_log')->where(['help_user_id'=>$this->uid, 'user_id'=>$user_id, 'prizes_id'=>$prizes_id])->order('id desc')->find();
				if($log){
					$this->ajaxReturn(['s'=>false, 'm'=>'您已帮他(她)签到过']);
				}
				break;
		}
		$data['num'] = $sign_in_num;
		$res = M('sign_in_log')->add($data);
		if($res){
			if($num+$sign_in_num >= $info['sign_in_num']){
				// 签到次数达到
				$data = [
					'user_id'		=> $data['user_id'],
					'prizes_id'		=> $prizes_id,
					'status'		=> 1,
					'create_time' 	=> $now_time,
				];
				M('winning')->add($data);
			}
			$this->ajaxReturn(['s'=>true, 'm'=>'提交成功']);
		}else{
			$this->ajaxReturn(['s'=>false, 'm'=>'提交失败']);
		}
	}

	public function sign_in_page()
	{
		$id = I('id');
		$info = M('prizes')->where(['id'=>$id])->field('id,title,sign_in_num,img,content,share_title,share_desc,list_img')->find();

		if($info){
			$num = M('sign_in_log')->where(['user_id'=>$this->uid, 'prizes_id'=>$id])->sum('num');
			$num = $num ? $num : 0;
			$log = M('sign_in_log')->alias('s')
					->join('__USER__ u ON s.help_user_id=u.id', 'left')
					->where(['s.user_id'=>$this->uid, 'type'=>'2', 's.prizes_id' => $id])
					->field('u.nickname,u.img,s.create_time as time')
					->select();
			if($log){
				foreach ($log as $key => &$row) {
					$row['time'] = date('Y-m-d H:i:s', $row['time']);
				}
			}
			$lingqv = 0;
			if(M('winning')->where(['user_id'=>$this->uid, 'prizes_id'=>$id])->find()){
				$lingqv = 1;
			}
			$this->ajaxReturn(['s'=>true, 'd'=>['info'=>$info, 'num'=>$num, 'log'=>$log, 'lingqv'=>$lingqv]]);
		}else{
			$this->ajaxReturn(['s'=>false]);
		}
	}

	/**
	 * 签到奖品地址
	 * @return [type] [description]
	 */
	public function award_address()
	{
		$id = I('id');
		$user_name = I('user_name');
		$mobile = I('mobile');
		$address = I('address');
		$winning = M('winning')->where(['user_id'=>$this->uid, 'prizes_id'=>$id])->find();
		if(empty($winning)){
			$this->ajaxReturn(['s'=>false, 'm'=>'您还没有得奖记录']);
		}
		$data = [
			'user_name'	=> $user_name,
			'mobile'	=> $mobile,
			'address'	=> $address,
			'status'	=> '2'
		];
		$res = M('winning')->where(['id'=>$winning['id']])->save($data);
		if($res !== false){
			$this->ajaxReturn(['s'=>true, 'm'=>'提交成功']);
		}else{
			$this->ajaxReturn(['s'=>false, 'm'=>'提交失败']);
		}
	}

	public function award_page()
	{
		$id = I('id');
		$winning = M('winning')->alias('w')
                ->join('__PRIZES__ p ON w.prizes_id=p.id', 'left')
                ->join('__USER__ u ON w.user_id=u.id', 'left')
                ->where(['w.user_id'=>$this->uid, 'w.prizes_id'=>$id])
                ->field('w.user_name,w.mobile,w.address,w.express,w.express_number,w.status,p.title,p.img')
                ->find();
		if(empty($winning)){
			$this->ajaxReturn(['s'=>false, 'm'=>'您还没有得奖记录']);
		}

		if($winning !== false){
			$this->ajaxReturn(['s'=>true, 'd'=>$winning]);
		}else{
			$this->ajaxReturn(['s'=>false]);
		}
	}

	public function img_verify($vid = 1)
	{ 
 		$verify = new \Think\ApiVerify([
            'useCurve' => false,
            'useNoise' => false,
            'fontSize' => 36,
            'reset'    => false,
        ]);
        $verify->length = 4;
        $verify->entry($vid);		
	}


	public function jc_check_member()
	{
		$info = M('nearby_shop')->where(['uid'=>$this->uid])->find();
		if(empty($info)){
			$this->ajaxReturn(['s'=>true, 'is_member'=>0, 'msg'=>'你还没有成为店铺，请先去申请']);
			// $this->ajaxReturn(['s'=>false, 'm'=>'请先申请成为附近麻将机店']);
		}
		if($info['member_grade'] >= 1){
			if($info['member_expire'] && $info['member_expire'] >= time()){
				$this->ajaxReturn(['s'=>true, 'is_member'=>1]);
			}
			$this->ajaxReturn(['s'=>true, 'is_member'=>0, 'msg'=>'你的账号已过期']);	
		}
		$this->ajaxReturn(['s'=>true, 'is_member'=>0, 'msg'=>"请先购买集采会员"]);
	}

	/**
	 * 采集中心
	 * @return [type] [description]
	 */
	public function jc_center()
	{
		// 轮播
		$slider =  M('slider')->where(['type'=>2])->order('id asc')->field('id,img,link')->select();
		// 分类
		$category = D('JcCategory')->where(['status'=>1, 'pid'=>0])->order('sort asc,id asc')->field('id,title,img')->select();
		if($category){
			foreach ($category as $key => &$row) {
				if($row['id'] == 4){
					$row['is_manage'] = 1;
				}else{
					$row['is_manage'] = 0;
				}
			}
		}
		// 公告
		$notice = yzl_config('jc.jc_center_notice');
		$this->ajaxReturn(['s'=>true, 'slider'=>$slider, 'notice'=>$notice, 'category'=>$category]);
	}

    /**
     * 集采管理中心
     * @return void
     */
    public function jc_manage_center()
	{
        $category_id = 4;
        $category = M('JcCategory')->where(['id'=>$category_id])->find();
		$category_title = $category ? $category['title'] : '';
		// 轮播
		// $slider_type = jc_category_to_slider_type($category_id);
		if(!empty($category['imgs'])){
			$slider =  explode(',', $category['imgs']);//M('slider')->where(['type'=>2])->order('id asc')->field('img,link')->select();	
		}else{
			$slider = [];
		}
		$customer_img = yzl_config('jc.jc_customer_img');
		$staff_img = yzl_config('jc.jc_staff_img');
		$report_img = yzl_config('jc.jc_sales_img');
		// 公告
        $notice = $category ? $category['notice'] : '';
		$type_arr = [
			['img'=>$customer_img, 'title'=>'客户管理'],
			['img'=>$staff_img, 'title'=>'员工管理'],
			['img'=>$report_img, 'title'=>'年度报表'],
		];
        $this->ajaxReturn(['s'=>true, 'category'=>$type_arr, 'category_title'=>$category_title, 'slider'=>$slider, 'notice'=>$notice]);
    }

	/**
	 * 集采中心商品列表
	 * @return [type] [description]
	 */
	public function jc_goods_list()
	{
		$category_id = I('category_id');
		$category = M('JcCategory')->where(['id'=>$category_id])->find();
		$category_title = $category ? $category['title'] : '';
		$category_list = M('JcCategory')->where(['pid'=>$category_id])->field('id,title')->order('sort asc,id asc')->select();
		// 轮播
		// $slider_type = jc_category_to_slider_type($category_id);
		if(!empty($category['imgs'])){
			$slider =  explode(',', $category['imgs']);//M('slider')->where(['type'=>2])->order('id asc')->field('img,link')->select();	
		}else{
			$slider = [];
		}
		// 公告
        $notice = $category ? $category['notice'] : '';

		// 商品列表
        $first_category = reset($category_list);
        if($first_category){
	        $map = [
	        	'category_id'	=> $first_category['id'],
	        	'status' 		=> 1,
	        ];
			$goods_list = M('jc_goods')->where($map)->field('id,goods_name,img,price,sales_num')->order('sort desc, id asc')->select();
        }else{
        	$goods_list = [];
        }
		$this->ajaxReturn(['s'=>true, 'category_title'=>$category_title, 'category_list'=>$category_list, 'slider'=>$slider, 'notice'=>$notice, 'goods_list'=>$goods_list]);
	}

	/**
	 * 集采搜索商品
	 * @return [type] [description]
	 */
	public function jc_search_goods()
	{
		$category_id = I('category_id');
		$map = [
        	'category_id'	=> $category_id,
        	'status' 		=> 1,
        ];
		$goods_list = M('jc_goods')->where($map)->field('id,goods_name,img,price,sales_num')->order('sort desc, id asc')->select();
		$this->ajaxReturn(['s'=>true, 'goods_list'=>$goods_list]);		
	}

	/**
	 * 集采商品详情
	 * @return [type] [description]
	 */
	public function jc_goods_detail()
	{
		$id = I('id');
		$info = M('JcGoods')->where(['id'=>$id, 'status'=>1])->find();
		if(empty($info)){
			$this->ajaxReturn(['s'=>false, 'm'=>'商品不存在']);
		}
		$info['imgs'] = $info['imgs'] ? explode(',', $info['imgs']) : [];
		
		$info['pro_attr'] = M('JcGoodsAttr')->where(['goods_id'=>$info['id']])->select();

		$this->ajaxReturn(['s'=>true, 'm'=>'成功', 'd'=>$info]);
	}

	/**
	 * 获取集采条款
	 * @Author   张亚伟<1743325520@qq.com>
	 * @DateTime 2018-05-09
	 * @return   [type]                 [description]
	 */
	public function get_jc_clause()
	{
		$clause = yzl_config('jc.js_clause');
		$this->ajaxReturn(['s'=>true, 'm'=>'成功', 'info'=>['clause'=>$clause]]);
	}

	/**
	 * 集采确认订单
	 * @return void
	 */
	public function jc_confirm_order()
	{
		$from = I('from');
		$wxpay_qr = yzl_config('jc.jc_wxpay_qr');
		$alipay_qr = yzl_config('jc.jc_alipay_qr');
		$bank_name = yzl_config('jc.jc_bank_name');
		$card_number = yzl_config('jc.jc_card_number');

		switch ($from) {
			case 'buynow':
				// 立即购买
				$goods_id = I('goods_id');
				$buy_num = I('buy_num');
				$attr_id = I('attr_id');
				$goods = M('JcGoods')->where(['id'=>$goods_id, 'status'=>1])->find();
				if(empty($goods)){
					$this->ajaxReturn(['s'=>false, 'm'=>'商品不存在或已被删除']);
				}
				$goods['attr_name'] = '';
				$attr = M('JcGoodsAttr')->where(['id'=>$attr_id])->find();
				if(!empty($attr)){
					if($attr['goods_id']!=$goods_id){
						$this->ajaxReturn(['s'=>false, 'm'=>'商品不存在该属性']);
					}
					$goods['price'] += $attr['dif'];
					$goods['stock_num'] = $attr['num'];
					$goods['attr_name'] = $attr['name'];
				}
				$goods['goods_id'] = $goods_id;
				$goods['goods_num'] = $buy_num;
				// if($goods['stock_num'] < $buy_num){
				// 	$this->ajaxReturn(['s'=>false, 'm'=>$goods['goods_name'].' '.$goods['attr_name'].' 库存不足']);
				// }
				$buy_List[] = $goods;
				$total_money = $goods['price']*$buy_num;
				$this->ajaxReturn(['s'=>true, 'm'=>'获取成功', 'list'=>$buy_List, 'total_money'=>sprintf("%.2f", $total_money), 'total_num'=>$buy_num, 'wxpay_qr'=>$wxpay_qr, 'alipay_qr'=>$alipay_qr, 'bank_name'=>$bank_name, 'card_number'=>$card_number]);
				break;
			case 'cart':
				// 购物车
				$cart_ids = I('cart_ids');
				$res = jc_cart_list($this->uid, $cart_ids);
				// if(!empty($res['cart_list'])){
				// 	foreach ($res['cart_list'] as $key => $goods) {
				// 		if($goods['stock_num'] < $goods['goods_num']){
				// 			$this->ajaxReturn(['s'=>false, 'm'=>$goods['goods_name'].' '.$goods['attr_name'].' 库存不足']);
				// 		}
				// 	}
				// }
				$this->ajaxReturn(['s'=>true, 'm'=>'获取成功', 'list'=>$res['cart_list'], 'total_money'=>sprintf("%.2f", $res['total_money']), 'total_num'=>$res['total_num'], 'wxpay_qr'=>$wxpay_qr, 'alipay_qr'=>$alipay_qr, 'bank_name'=>$bank_name, 'card_number'=>$card_number]);
				break;
			default:
				$this->ajaxReturn(['s'=>false, 'm'=>'类型错误']);
				break;
		}

	}

	/**
	 * 集采创建订单
	 * @return void
	 */
	public function jc_goods_order()
	{
		$from = I('from');
		$addid = I('addid');
		$gift_id = I('gift_id', 0);
		$pay_money = I('pay_money', 0);
		$addr = M('addr')->where(array('id' => $addid))->find();
		if(empty($addr)){
			$this->ajaxReturn(['s'=>false, 'm'=>'请添加收货地址']);
		}
		switch ($from) {
			case 'buynow':
				// 立即购买
				$goods_id = I('goods_id');
				$buy_num = I('buy_num');
				$attr_id = I('attr_id');
				$goods = M('JcGoods')->where(['id'=>$goods_id, 'status'=>1])->find();
				if(empty($goods)){
					$this->ajaxReturn(['s'=>false, 'm'=>'商品不存在或已被删除']);
				}
				$goods['attr_name'] = '';
				$attr = M('JcGoodsAttr')->where(['id'=>$attr_id])->find();
				if(!empty($attr)){
					if($attr['goods_id']!=$goods_id){
						$this->ajaxReturn(['s'=>false, 'm'=>'商品不存在该属性']);
					}
					$goods['price'] += $attr['dif'];
					$goods['stock_num'] = $attr['num'];
					$goods['attr_name'] = $attr['name'];
				}

				if($goods['stock_num'] < $buy_num){
					$this->ajaxReturn(['s'=>false, 'm'=>$goods['goods_name'].' '.$goods['attr_name'].' 库存不足']);
				}

				$goods['attr_id'] = $attr_id;
				$goods['goods_id'] = $goods_id;
				$goods['goods_num'] = $buy_num;
				$buy_List[] = $goods;
				$total_money = $goods['price']*$buy_num;
				break;
			case 'cart':
				// 购物车
				$cart_ids = I('cart_ids');
				$res = jc_cart_list($this->uid, $cart_ids);

				if(!empty($res['cart_list'])){
					foreach ($res['cart_list'] as $key => $goods) {
						if($goods['stock_num'] < $goods['goods_num']){
							$this->ajaxReturn(['s'=>false, 'm'=>$goods['goods_name'].' '.$goods['attr_name'].' 库存不足']);
						}
					}
				}
				$buy_List = $res['cart_list'];
				$total_money = $res['total_money'];
				break;
			default:
				$this->ajaxReturn(['s'=>false, 'm'=>'类型错误']);
				break;
		}
		// 订单商品数据
		$order_goods = [];
		foreach ($buy_List as $key => $goods) {
			if($goods['stock_num'] < $goods['goods_num'] || $goods['stock_num'] == 0){
				$this->ajaxReturn(['s'=>false, 'm'=>'库存不足']);
			}
			if($goods['status'] != 1){
				if(count($buy_List) == 1){
					$this->ajaxReturn(['s'=>false, 'm'=>'商品已下架']);
				}else{
					$this->ajaxReturn(['s'=>false, 'm'=>$goods['goods_name'].' 已下架']);
				}
			}
			$item = [
				'goods_id'		=> $goods['goods_id'],
				'attr_id'		=> $goods['attr_id'],
				'attr_name'		=> $goods['attr_name'],
				'goods_name'	=> $goods['goods_name'],
				'img'			=> $goods['img'],
				'buy_num'		=> $goods['goods_num'],
				'price'			=> $goods['price'],
			];
			$order_goods[] = $item;
		}
		$now_time = time();
		// 订单号
		$order_sn = 'JC'.$this->order_num();
		// 订单信息
		$order = [
			'user_id'			=> $this->uid,// 用户id
			'order_sn'			=> $order_sn,// 订单号
			'order_type'		=> 'goods',// 类型为商品订单类型
			'gift_id'			=> $gift_id,// 选择的兑换商品id
			'order_status'		=> 1,// 订单状态
			'pay_status'		=> 1,// 支付状态
			'shipping_status'	=> 0,// 发货状态
			'pay_voucher'		=> $this->uploadimgsy('pay_voucher'),// 支付凭证
			'pay_money'			=> $pay_money,// 支付金额
			'order_money'		=> $total_money,// 订单商品价格合计
			'user_name'			=> $addr['c_name'],// 姓名
			'phone'				=> $addr['c_phome'],// 手机号
			'pro'				=> $addr['pro'],// 省份
			'city'				=> $addr['city'],// 城市
			'area'				=> $addr['area'],// 地区
			'address'			=> $addr['add'],// 详细地址
			'create_time'		=> $now_time,// 创建时间
			'pay_time'			=> $now_time,// 支付时间
			'update_time'		=> $now_time,// 更新时间
		];

		$orderModel = M('JcOrder');
		$orderGoodsModel = M('JcOrderGoods');
		$goodsModel = M('JcGoods');
		$attrModel = M('JcGoodsAttr');
		$orderModel->startTrans();
		// 创建订单
		$order_id = $orderModel->add($order);
		if(!$order_id){
			$msg = '创建订单失败';
			goto jc_goods_order_done;
		}
		
		foreach ($order_goods as $key => &$row) {
			$row['order_id'] = $order_id;
			// 减库存
			if($row['attr_id']){
				$res = $attrModel->where(['id'=>$row['attr_id']])->setDec('num', $row['buy_num']);
				if($res===false){
					$msg = '创建订单失败';
					goto jc_goods_order_done;
				}
			}else{
				$res = $goodsModel->where(['id'=>$row['goods_id']])->setDec('stock_num', $row['buy_num']);
				if($res===false){
					$msg = '创建订单失败';
					goto jc_goods_order_done;
				}
			}
		}
		// 创建订单商品
		$res = $orderGoodsModel->addAll($order_goods);
		if($res===false){
			$msg = '创建订单失败';
			goto jc_goods_order_done;
		}

		jc_goods_pay_complete($order_id);
		jc_goods_order_done:
		if($msg){
			$orderModel->rollback();
			$this->ajaxReturn(['s'=>false, 'm'=>$msg]);
		}else{
			$orderModel->commit();
			// 删除购物车
			if($from == 'cart') {
				M('JcCart')->where(['id' => ['in', $cart_ids], 'user_id' => $this->uid])->delete();
			}
			$this->ajaxReturn(['s'=>true, 'm'=>'提交成功', 'order_sn'=>$order_sn]);
		}
	}


	/**
	 * 集采客服
	 * @return void
	 */
	public function jc_service()
	{
		$lsit = M('JcService')->select();
		// $img = yzl_config('jc.jc_service_img');
		$this->ajaxReturn(['s'=>true, 'm'=>'ok', 'lsit'=>$lsit]);
	}

	/**
	 * 集采礼品
	 * @return void
	 */
	public function jc_gift(){
		$money = I('money');
		$list = M('JcGift')->where(['money'=>['elt', $money]])->select();
		$this->ajaxReturn(['s'=>true, 'm'=>'ok', 'list'=>$list]);
	}

	/**
	 * 集采订单列表
	 * @return void
	 */
	public function jc_order_list(){
		$type = I('type');
		$page = I('page');
		$map = ['user_id'=>$this->uid, 'order_type'=>'goods', 'del_status'=>0];
		switch ($variable) {
			case '1':
				// 待付款
				$map['order_status'] = 1;
				$map['pay_status'] = 0;
				break;
			case '2':
				// 待发货
				$map['order_status'] = 1;
				$map['shipping_status'] = 0;
				break;
			case '3':
				// 待收货
				$map['order_status'] = 1;
				$map['shipping_status'] = 1;
				break;
			case '4':
				// 已完成
				$map['order_status'] = 2;
				break;
		}
		$orderModel = M('JcOrder');
		if($page){
			$order_list = $orderModel->where($map)->field('id,order_sn,pay_money,order_money,create_time,order_status,pay_status,shipping_status,del_status')->order('id desc')->page($page, 20)->select();
		}else{
			$order_list = $orderModel->where($map)->field('id,order_sn,pay_money,order_money,create_time,order_status,pay_status,shipping_status,del_status')->order('id desc')->select();
		}
		if($order_list){
			if($order_ids = array_column($order_list, 'id')){
				$order_goods = M('JcOrderGoods')->where(['order_id'=>['in', $order_ids]])->field('id,order_id,goods_name,attr_name,img,price,buy_num')->select();
			}else{
				$order_goods = [];
			}
			foreach ($order_list as $key => &$order) {
				// 创建时间
				$order['create_time'] = date('Y-m-d H:i:s', $order['create_time']);
				// 订单商品
                $og_arr = list_search($order_goods, ['order_id'=>$order['id']]);
                $og_arr = array_combine(range(0, count($og_arr) - 1), $og_arr);
				$order['order_goods'] = $og_arr;//isset($order_goods[$order['id']]) ? $order_goods[$order['id']] : [];
				// 订单按钮
				$order['buttons'] = jc_order_bnt($order);
				// 订单状态
				$order['status_msg'] = jc_order_status_msg($order);
				unset($order['order_status']);
				unset($order['pay_status']);
				unset($order['shipping_status']);
			}
		}
		$this->ajaxReturn(['s'=>true, 'order_list'=>$order_list]);
	}
	
	/**
	 * 集采订单详情
	 */
	public function jc_order_detail() {
		$order_id = I('order_id');
		$order = M('JcOrder')->where(['id'=>$order_id])->field('id,order_sn,pay_money,order_money,order_status,pay_status,shipping_status,del_status,user_id,gift_id,pay_voucher,user_name,phone,pro,city,area,address,shipping_code,shipping_name,create_time')->find();
		if(empty($order) || $order['user_id'] != $this->uid){
			$this->ajaxReturn(['s'=>false, 'm'=>'订单不存在或已被删除']);
		}
		// 创建时间
		$order['create_time'] = date('Y-m-d H:i:s', $order['create_time']);
		// 订单按钮
		$order['buttons'] = jc_order_bnt($order);
        // 订单状态
        $order['status_msg'] = jc_order_status_msg($order);
		// 礼品
		$gift = [];
		if($order['gift_id']){
			$gift = M('JcGift')->where(['id'=>$order['gift_id']])->find();
		}
		// 平台热线
		$hotline = yzl_config('jc.jc_order_hotline');
		// 意见
		$model = D('Api/JcFeedback');
		$feedback = $model->where(['order_id'=>$order_id])->find();
		// 订单商品
		$order_goods = M('JcOrderGoods')->where(['order_id'=>$order['id']])->select();
		// 返回数据
		$res = ['s'=>true, 'm'=>'ok', 'order'=>$order, 'hotline'=>$hotline, 'is_feedback'=>0, 'order_goods'=>$order_goods];
		if($gift){
			$res ['gift'] = $gift;
		}
		if($feedback){
			$res['is_feedback'] = 1;
			$res['feedback_content'] = $feedback['content'];
		}
		$this->ajaxReturn($res);
	}

	/**
	 * 集采意见箱
	 * @return void
	 */
	public function jc_feedback(){
		$order_id = I('order_id');
		$orderModel = M('JcOrder');
		$order = $orderModel->where(['id'=>$order_id])->find();
		if (empty($order) || $order['user_id'] != $this->uid) {
			$this->ajaxReturn(['s'=>false, 'm'=>'订单不存在或已被删除']);
		}
		$model = D('Api/JcFeedback');
		$has = $model->where(['order_id'=>$order_id])->find();
		if($has){
			$this->ajaxReturn(['s'=>false, 'm'=>'已提交过']);
		}
		$data = I('post.');
		$data['user_id'] = $this->uid;
		if($model->create($data)){
			$insertId = $model->add(); // 写入数据到数据库
			if ($insertId) {
				$this->ajaxReturn(['s'=>true, 'm'=>'提交成功']);
			}else{
				$this->ajaxReturn(['s'=>false, 'm'=>'提交失败']);
			}
		}else{
			$this->ajaxReturn(['s'=>false, 'm'=>$model->getError()]);
		}
	}

	/**
	 * 更新集采商品订单状态
	 * @return void
	 */
	public function jc_order_status() {
		$order_id = i('order_id');
		$action = I('action');
		$orderModel = M('JcOrder');
		$order = $orderModel->where(['id'=>$order_id])->find();
		if (empty($order) || $order['user_id'] != $this->uid) {
			$this->ajaxReturn(['s'=>false, 'm'=>'订单不存在或已被删除']);
		}
		switch ($action) {
			case 'confirm_receipt':
				if($order['ordre_status'] == 2){
					$this->ajaxReturn(['s'=>false, 'm'=>'订单已完成']);
				}
				if(in_array($order['order_status'], [-1, 0])){
					$this->ajaxReturn(['s'=>false, 'm'=>'订单交易已被关闭']);
				}
				if($order['shipping_status'] != 1){
					$this->ajaxReturn(['s'=>false, 'm'=>'订单还未发货']);
				}
				$save_data = [
					'order_status'	=> 2,
					'update_time'	=> time()
				];
				$res = $orderModel->where(['id'=>$order_id])->save($save_data);
				if($res !== false){
					$this->ajaxReturn(['s'=>true, 'm'=>'操作成功']);
				}else{
					$this->ajaxReturn(['s'=>false, 'm'=>'操作失败']);
				}
				break;
			case 'delete':
				$save_data = [
					'del_status'	=> 1,
					'update_time'	=> time()
				];
				$res = $orderModel->where(['id'=>$order_id])->save($save_data);
				if($res !== false){
					$this->ajaxReturn(['s'=>true, 'm'=>'操作成功']);
				}else{
					$this->ajaxReturn(['s'=>false, 'm'=>'操作失败']);
				}
				break;
			default:
				$this->ajaxReturn(['s'=>false, 'm'=>'action参数错误']);
				break;
		}
	}

	/**
	 * 集采员工
	 * @return void
	 */
	public function jc_staff() {
		$page = I('page');
		$map = ['user_id'=>$this->uid];
		if($page){
			$data_list = M('JcStaff')->where($map)->page($page, 20)->field('id,user_name,phone,address,position')->select();
		}else{
			$data_list = M('JcStaff')->where($map)->field('id,user_name,phone,address,position')->select();
		}
		// 职位
		$position = yzl_config('jc.jc_staff_position');
		foreach ($data_list as $key => &$row) {
			$row['position'] = isset($position[$row['position']]) ? $position[$row['position']] : '';
		}
		$this->ajaxReturn(['s'=>true, 'm'=>'ok', 'list'=>$data_list]);
	}

	/**
	 * 集采员工编辑需要的配置数据
	 * @return void
	 */
	public function jc_staff_config() {
		// 职位
		$position = yzl_config('jc.jc_staff_position');
		// 性别
		$sex = yzl_config('jc.jc_sex');
		// 学历
		$education = yzl_config('jc.jc_staff_education');
		$this->ajaxReturn(['s'=>true, 'm'=>'ok', 'position'=>$position, 'sex'=>$sex, 'education'=>$education]);
	}
	
	public function jc_staff_add() {
		$data = I('post.');
        $wages = I('wages/a', []);
        $emergency_1 = I('emergency_1');
        $emergency_2 = I('emergency_2');
        $data['wages'] = json_encode($wages);
        $data['emergency_contact'] = $emergency_1.','.$emergency_2;
		$data['user_id'] = $this->uid;
		$shop = M('nearby_shop')->where(['uid' => $this->uid])->find();
		if($shop){
			$data['shop_id'] = $shop['id'];
		}
		$model = D('Api/JcStaff');
		if($model->create($data)){
			$insertId = $model->add(); // 写入数据到数据库
			if ($insertId) {
				$this->ajaxReturn(['s'=>true, 'm'=>'提交成功']);
			}else{
				$this->ajaxReturn(['s'=>false, 'm'=>'提交失败']);
			}
		}else{
			$this->ajaxReturn(['s'=>false, 'm'=>$model->getError()]);
		}
	}

    /**
     * 集采员工信息
     * @return void
     */
	public function jc_staff_info() {
		$id = I('id');
		$model = D('Api/JcStaff');
		$info = $model->where(['id'=>$id])->find();
		if(empty($info) || $info['user_id']!=$this->uid){
			$this->ajaxReturn(['s'=>false, 'm'=>"信息不存在"]);
		}
        $info['wages'] = empty($info['wages']) ? [] : json_decode($info['wages'], true);
        $contact = explode(',', $info['emergency_contact']);
        $info['emergency_1'] = isset($contact[0]) ? $contact[0] : '';
        $info['emergency_2'] = isset($contact[1]) ? $contact[1] : '';
		// 职位
		$position = yzl_config('jc.jc_staff_position');
		// 性别
		$sex = yzl_config('jc.jc_sex');
		// 学历
		$education = yzl_config('jc.jc_staff_education');
		$this->ajaxReturn(['s'=>true, 'm'=>'ok', 'info'=>$info, 'position'=>$position, 'sex'=>$sex, 'education'=>$education]);
	}

	public function jc_staff_edit() {
		$id = I('id');
		$data = I('post.');
        $wages = I('wages/a', []);
        $emergency_1 = I('emergency_1');
        $emergency_2 = I('emergency_2');
        $data['wages'] = json_encode($wages);
        $data['emergency_contact'] = $emergency_1.','.$emergency_2;
		$data['user_id'] = $this->uid;
		$model = D('Api/JcStaff');
		if($model->create($data)){
            $res = $model->where(['id'=>$id, 'user_id'=>$this->uid])->save();
            if($res){
                $this->ajaxReturn(['s'=>true, 'm'=>'修改成功']);
            }else{
			    $this->ajaxReturn(['s'=>false, 'm'=>'修改失败']);
            }
        }else{
			$this->ajaxReturn(['s'=>false, 'm'=>$model->getError()]);
        }
	}

	/**
	 * 集采员工删除
	 * @return void
	 */
	public function jc_staff_del() {
		$ids = I('ids');
		if(empty($ids)){
			$this->ajaxReturn(['s'=>false, 'm'=>'请选择删除项']);
		}
		$res = D('Api/JcStaff')->where(['id'=>['in', $ids], 'user_id'=>$this->uid])->delete();
		if($res!==false){
			$this->ajaxReturn(['s'=>true, 'm'=>'删除成功']);
		}else{
			$this->ajaxReturn(['s'=>false, 'm'=>'删除失败']);
		}
	}
	
	/**
	 * 集采客户列表
	 * @return void
	 */
    public function jc_customer() {
		$page = I('page');
		$model = D('Api/JcCustomer');
		if($page){
			$data_list = $model->where(['user_id'=>$this->uid])->page($page, 20)->field('id,customer_name,phone,address')->select();
		}else{
			$data_list = $model->where(['user_id'=>$this->uid])->field('id,customer_name,phone,address')->select();
		}
		$this->ajaxReturn(['s'=>true, 'm'=>'ok', 'list'=>$data_list]);
	}
	
	/**
	 * 集采添加客户
	 * @return void
	 */
	public function jc_customer_add(){
		$data = I('post.');
		$goods = I('goods/a', []);
		$data['goods'] = json_encode($goods);
		$data['user_id'] = $this->uid;
		$shop = M('nearby_shop')->where(['uid' => $this->uid])->find();
		if($shop){
			$data['shop_id'] = $shop['id'];
		}
		$model = D('Api/JcCustomer');
		if($model->create($data)){
			$insertId = $model->add();
			if($insertId){
				$this->ajaxReturn(['s'=>true, 'm'=>'添加成功']);
			}else{
				$this->ajaxReturn(['s'=>false, 'm'=>'添加失败']);
			}
		}else{
			$this->ajaxReturn(['s'=>false, 'm'=>$model->getError()]);
		}
	}

	/**
	 * 集采获取客户信息
	 * @return void
	 */
	public function jc_customer_info(){
		$id = I('id');
		$info = D('Api/JcCustomer')->where(['id'=>$id])->find();
		if(empty($info) || $info['user_id'] != $this->uid){
			$this->ajaxReturn(['s'=>false, 'm'=>'信息不存在']);
		}
		$info['goods'] = empty($info['goods']) ? [] : json_decode($info['goods'], true);
		$this->ajaxReturn(['s'=>true, 'm'=>'ok', 'info'=>$info]);
	}

	/**
	 * 集采编辑客户
	 * @return void
	 */
	public function jc_customer_edit(){
		$id = I('id');
		$data = I('post.');
		$goods = I('goods/a', []);
		$data['goods'] = json_encode($goods);
		$model = D('Api/JcCustomer');
		if($model->create($data)){
			$res = $model->where(['id'=>$id, 'user_id'=>$this->uid])->save();
			if($res !== false){
				$this->ajaxReturn(['s'=>true, 'm'=>'修改成功']);
			}else{
				$this->ajaxReturn(['s'=>false, 'm'=>'修改失败']);
			}
		}else{
			$this->ajaxReturn(['s'=>false, 'm'=>$model->getError()]);
		}
	}

	/**
	 * 集采删除客户
	 * @return void
	 */
	public function jc_customer_del(){
		$ids = I('ids');
		if(empty($ids)){
			$this->ajaxReturn(['s'=>false, 'm'=>'请选择删除项']);
		}
		$res = D('Api/JcCustomer')->where(['id'=>['in', $ids], 'user_id'=>$this->uid])->delete();
		if($res!==false){
			$this->ajaxReturn(['s'=>true, 'm'=>'删除成功']);
		}else{
			$this->ajaxReturn(['s'=>false, 'm'=>'删除失败']);
		}
	}

	/**
	 * 集采年度报表
	 * @return void
	 */
	public function jc_annual_report() {
		$page = I('page');
		$model = D('Api/JcSales');
		if($page){
			$list = $model->where(['user_id'=>$this->uid])->page($page, 20)->order('id desc')->field('id,month_sales,month_total_sales')->select();
		}else{
			$list = $model->where(['user_id'=>$this->uid])->order('id desc')->field('id,month_sales,month_total_sales')->select();
		}
		$this->ajaxReturn(['s'=>true, 'm'=>'ok', 'list'=>$list]);
	}
	/**
	 * 集采添加年度报表
	 * @return void
	 */
	public function jc_report_add(){
		$data = I('post.');
		$daily_sales = I('daily_sales/a', []);
		$data['user_id'] = $this->uid;
		$data['daily_sales'] = json_encode($daily_sales);
		$shop = M('nearby_shop')->where(['uid' => $this->uid])->find();
		if($shop){
			$data['shop_id'] = $shop['id'];
		}
		$model = D('Api/JcSales');
		if($model->create($data)){
			$insertId = $model->add();
			if($insertId){
				$this->ajaxReturn(['s'=>true, 'm'=>'添加成功']);
			}else{
				$this->ajaxReturn(['s'=>false, 'm'=>'添加失败']);
			}
		}else{
			$this->ajaxReturn(['s'=>false, 'm'=>$model->getError()]);
		}
	}

	/**
	 * 集采获取年度报表信息
	 * @return void
	 */
	public function jc_report_info(){
		$id = I('id');
		$info = D('Api/JcSales')->where(['id'=>$id])->find();
		if(empty($info) || $info['user_id'] != $this->uid){
			$this->ajaxReturn(['s'=>false, 'm'=>'信息不存在']);
		}
		$info['daily_sales'] = empty($info['daily_sales']) ? [] : json_decode($info['daily_sales'], true);
		$this->ajaxReturn(['s'=>true, 'm'=>'ok', 'info'=>$info]);
	}

	/**
	 * 集采修改年度报表
	 * @return void
	 */
	public function jc_report_edit(){
		$id = I('id');
		$data = I('post.');
		$daily_sales = I('daily_sales/a', []);
		$data['daily_sales'] = json_encode($daily_sales);
		$model = D('Api/JcSales');
		if($model->create($data)){
			$res = $model->where(['id'=>$id, 'user_id'=>$this->uid])->save();
			if($res !== false){
				$this->ajaxReturn(['s'=>true, 'm'=>'修改成功']);
			}else{
				$this->ajaxReturn(['s'=>false, 'm'=>'修改失败']);
			}
		}else{
			$this->ajaxReturn(['s'=>false, 'm'=>$model->getError()]);
		}
	}

	/**
	 * 集采删除年度报表
	 * @return void
	 */
	public function jc_report_del(){
		$ids = I('ids');
		if(empty($ids)){
			$this->ajaxReturn(['s'=>false, 'm'=>'请选择删除项']);
		}
		$res = D('Api/JcSales')->where(['id'=>['in', $ids], 'user_id'=>$this->uid])->delete();
		if($res!==false){
			$this->ajaxReturn(['s'=>true, 'm'=>'删除成功']);
		}else{
			$this->ajaxReturn(['s'=>false, 'm'=>'删除失败']);
		}
	}
	
	public function jc_cart_list(){
		$res = jc_cart_list($this->uid);

		// 分类
		$category = D('JcCategory')->where(['id'=>['in', [1, 2, 3]]])->order('sort asc,id asc')->field('id,title,img')->select();

		$this->ajaxReturn(['s'=>true, 'm'=>'获取成功', 'category'=>$category, 'list'=>$res['cart_list'], 'total_money'=>$res['total_money'], 'total_num'=>$res['total_num']]);
	}

	public function jc_cart_edit(){
		$goods_id = I('goods_id');
		$attr_id = I('attr_id', 0);
		$num = I('num');

		$goods = M('JcGoods')->where(['goods_id'=>$goods_id, 'status'=>1])->find();
		if(empty($goods)){
			$this->ajaxReturn(['s'=>false, 'm'=>'商品不存在或已被删除']);
		}
		$attr = M('JcGoodsAttr')->where(['id'=>$attr_id])->find();
		if(!empty($attr)){
			if($attr['goods_id']!=$goods_id){
				$this->ajaxReturn(['s'=>false, 'm'=>'商品不存在该属性']);
			}
			$goods['price'] += $attr['dif'];
			$goods['stock_num'] += $attr['num'];
		}

		$data = [
			'user_id'	=> $this->uid,
			'goods_id'	=> $goods_id,
			'attr_id'	=> $attr_id,
		];
		$cartModel = M('JcCart');
		$cart = $cartModel->where(['user_id'=>$this->uid, 'goods_id'=>$goods_id, 'attr_id'=>$attr_id])->find();
		if($cart){
			$edit_num = $cart['goods_num'] + $num;
			if(($goods['stock_num'] < $edit_num || $goods['stock_num'] == 0) && $num > 0){
				$this->ajaxReturn(['s'=>false, 'm'=>'库存不足']);
			}
			if($edit_num < 1){
				$this->ajaxReturn(['s'=>false, 'm'=>'数量必须大于等于1']);
			}
			$data['goods_num'] = $edit_num;
			$res = $cartModel->where(['id'=>$cart['id']])->save($data);
			if($res !== fasle){
				$this->ajaxReturn(['s'=>true, 'm'=>'修改成功']);
			}else{
				$this->ajaxReturn(['s'=>false, 'm'=>'修改失败']);
			}

		}else{
			if($num < 1){
				$this->ajaxReturn(['s'=>false, 'm'=>'数量必须大于等于1']);
			}
			if($goods['stock_num'] < $num || $goods['stock_num'] == 0){
				$this->ajaxReturn(['s'=>false, 'm'=>'库存不足']);
			}
			$data['goods_num'] = $num;
			$data['create_time'] = time();
			$res = $cartModel->add($data);
			if($res){
				$this->ajaxReturn(['s'=>true, 'm'=>'加入成功']);
			}else{
				$this->ajaxReturn(['s'=>false, 'm'=>'添加失败']);
			}
		}
	}

	public function jc_cart_del()
	{
		$ids = I('ids');
		if(empty($ids)){
			$this->ajaxReturn(['s'=>false, 'm'=>'请选择删除项']);
		}
		$ids = explode(',', $ids);
		$res = M('JcCart')->where(['id'=>['in', $ids], 'user_id'=>$this->uid])->delete();
		if($res !== false){
			$this->ajaxReturn(['s'=>true, 'm'=>'删除成功']);
		}else{
			$this->ajaxReturn(['s'=>false, 'm'=>'删除失败']);
		}
	}

	/**
	 * 集采充值中心
	 * @return [type] [description]
	 */
	public function jc_cz_center()
	{
		$user = M('user')->where(['id'=>$this->uid])->field('nickname,img')->find();
		if(empty($user)){
			$user['nickname'] = '';
			$user['img'] = '';
		}
		$cz_arr = get_jc_cz();

		$this->ajaxReturn(['s'=>true, 'user'=>$user, 'chongzhi'=>$cz_arr]);
	}

	/**
	 * 创建集采会员订单
	 * @return [type] [description]
	 */
	public function jc_member_corder()
	{
		$order_type = I('order_type');// member vip_member
		$pay_type = I('pay_type');// 支付方式
		$jc_cz = get_jc_cz();
		if(!in_array($order_type, array_column($jc_cz, 'order_type'))){
			$this->ajaxReturn(['s'=>false, 'm'=>'会员类型不存在']);
		}
		$shop = M('nearby_shop')->where(['uid'=>$this->uid])->find();
		if(empty($shop)){
			$this->ajaxReturn(['s'=>false, 'm'=>'你还没有成为店铺，请先去申请']);
		}
		// if(!in_array($pay_type, ['wxpay', 'alipay'])){
		// 	$this->ajaxReturn(['s'=>false, 'm'=>'支付方式不存在']);
		// }
		$lx = list_search($jc_cz, ['order_type'=>$order_type]);
		$order_sn = 'JC'.$this->order_num();
		$order_data	 = [
			'user_id'		=> $this->uid,
			'order_type'	=> $order_type,
			// 'pay_type'		=> $pay_type,
			'order_sn'		=> $order_sn,
			'pay_money'		=> reset($lx)['price'],
			'pay_status'	=> 0,
			'create_time'	=> time(),
			'update_time'	=> time(),
		];

		$model = M('jc_order');
		$model->add($order_data);
		$this->ajaxReturn(['s'=>true, 'm'=>'创建成功', 'd'=>$order_sn]);
	}

	/**
	 * 获取打开app的广告
	 * @return [type] [description]
	 */
	public function app_open_ad()
	{
		$appad_img = yzl_config('appad.appad_img');
		$appad_url = yzl_config('appad.appad_url');
		$appad_status = yzl_config('appad.appad_status');
		if($appad_status){
			$this->ajaxReturn(['s'=>true, 'm'=>'ok', 'ad'=>['img'=>$appad_img, 'url'=>$appad_url]]);	
		}else{
			$this->ajaxReturn(['s'=>false, 'm'=>'暂无广告']);
		}
	}

	/**
	 * 轮播获取
	 * @Author   张亚伟<1743325520@qq.com>
	 * @DateTime 2018-10-11
	 */
	public function get_slider()
	{
		$type = I('type');
		// 轮播
		$slider =  M('slider')->where(['type'=>$type])->order('id asc')->field('id,img,link')->select();
		$this->ajaxReturn(['s'=>true, 'm'=>'ok', 'list'=>$slider]);
	}

	/**
	 * 首页商品获取
	 * @Author   张亚伟<1743325520@qq.com>
	 * @DateTime 2018-10-11
	 */
	public function home_goods()
	{
		$category_id = I('category_id');
		$price = I('price');
		$page = I('page', 1);
		$size = I('size', 0);
		$map = [];
		if($category_id){
			$map['cid'] = $category_id;
		}
		$map['status'] = 1;

		if($price){
			$price = explode('-', $price);
			if(isset($price[0]) && isset($price[1])){
				$map['price'] = ['between', [$price[0], $price[1]]];
			}
		}
		if($page && $size){
			$list = M('product')->where($map)->order('sort desc,id asc')->page($page, $size)->field('id,title,listimg,price,sales,pinglun')->select();
		}else{
			$list = M('product')->where($map)->order('sort desc,id asc')->field('id,title,listimg,price,sales,pinglun')->select();
		}
		$attrModel = M('product_attr');
		foreach ($list as $key => &$row) {
			$row['store_num'] = $attrModel->where(['pid'=>$row['id']])->sum('num');
			$row['store_num'] = $row['store_num'] ? $row['store_num'] : 0;
		}
		$this->ajaxReturn(['s'=>true, 'm'=>'ok', 'list'=>$list]);
	}

	/**
	 * 首页商品筛选类型
	 * @author 张亚伟<1743325520@qq.com>
	 * @DateTime 2018-10-15
	 * @return   [type]     [description]
	 */
	public function home_goods_filter()
	{
		$img = yzl_config('product.filter_price_top_img');
		$filter_price = yzl_config('product.filter_price');
		$list = [];
		// // 价格筛选
		// if($filter_price){
		// 	foreach ($filter_price as $key => $filter) {
		// 		$list[] = [
		// 			'name'		=> $filter,
		// 			'is_price'	=> 1,
		// 		];
		// 	}
		// }
		// 分类筛选
		$category = M('product_category')->where(['status'=>1])->order('sort desc')->field('id,category')->select();
		if($category){
			foreach ($category as $key => $c) {
				$list[] = [
					'id'		=> $c['id'],
					'name'		=> $c['category'],
					'is_price'	=> 0,
				];
			}
		}
		$this->ajaxReturn(['s'=>true, 'm'=>'ok', 'list'=>$list, 'img'=>$img]);
	}

	/**
	 * 获取会员管家号列表
	 * @Author   张亚伟<1743325520@qq.com>
	 * @DateTime 2018-10-12
	 * @return   [type]                 [description]
	 */
	public function get_member_no()
	{
		$page = I('page', 1);
		$size = I('size', 20);
		$model = M();
		$not_time = time();
		$month_time = month_time();
		$start = ($page - 1)*$size;

		$sql = "SELECT mn.*,sum(ml.like_num) as like_num FROM __MEMBER_NO__ as mn LEFT JOIN __MEMBER_NO_LIKE__ as ml ON mn.id=ml.member_no_id WHERE mn.id IS NOT NULL AND ml.create_time >={$month_time[0]} AND ml.create_time <={$month_time[1]} GROUP BY mn.id,ml.user_id ORDER BY like_num DESC,mn.like_time ASC,mn.id ASC LIMIT $start,$size";

		$list = $model->query($sql);
		$this->ajaxReturn(['s'=>true, 'm'=>'ok', 'list'=>$list]);
	}

	/**
	 * 会员号往期冠军
	 * @Author   张亚伟<1743325520@qq.com>
	 * @DateTime 2018-10-12
	 * @return   [type]                 [description]
	 */
	public function mn_past_gj()
	{
		$start = I('start', 1);
		$past_num = I('past_num', 10);

		$list = [];
		$model = M();
		$min_time = M('member_no_like')->min('create_time');
		if($min_time){
			$last_month = month_time(strtotime("-1 month"));
			$cur_period = getMonthNum(date('Y-m-d', $last_month[0]), date('Y-m-d', $min_time))+1;
			for ($i=$start; $i <= $past_num; $i++) {
				$month_time = month_time(strtotime("-{$i} month"));
				if($month_time[1] >= $min_time){
					$sql = "SELECT mn.*,sum(ml.like_num) as like_num FROM __MEMBER_NO__ as mn LEFT JOIN __MEMBER_NO_LIKE__ as ml ON mn.id=ml.member_no_id WHERE mn.id IS NOT NULL AND ml.create_time >={$month_time[0]} AND ml.create_time <={$month_time[1]} GROUP BY mn.id,ml.user_id ORDER BY like_num DESC,mn.like_time ASC,mn.id ASC LIMIT 0,10";
					$gj_users = $model->query($sql);
					$date = date('Y年m月', $month_time[0]);
					if($gj_users){
						foreach ($gj_users as $key => &$user) {
							$gj_info = M('member_no_gj')->where(['date'=>$date, 'rank'=>($key+1)])->find();
							if($gj_info){
								$user['goods_name'] = $gj_info['goods_name'];
							}else{
								$user['goods_name'] = '正在计算奖品，请稍后';
							}
						}
					}
					$list[] = [
						'users'	=> $gj_users,
						'date'	=> $date,
						'period'=> $cur_period - ($i - 1),
					];
				}
			}
		}
		$this->ajaxReturn(['s'=>true, 'm'=>'ok', 'list'=>$list]);
	}

	/**
	 * 我的会员号信息
	 * @Author   张亚伟<1743325520@qq.com>
	 * @DateTime 2018-10-12
	 * @return   [type]                 [description]
	 */
	public function my_member_no()
	{
		$info = M('member_no')->where(['user_id'=>$this->uid])->find();
		if(empty($info)){
			$this->ajaxReturn(['s'=>false, 'm'=>'您还没有会员号']);
		}
		// 本月开始时间和结束时间
		$month_time = month_time();
		$last_like = M('member_no_like')->where(['user_id'=>$this->uid, 'create_time'=>['between', [$month_time[0], $month_time[1]]]])->order('id desc')->field('id,sum(like_num) as like_num,create_time')->find();
		$sql = "";
		$rank = 0;
		$like_num = 0;
		if($last_like){
			$like_num = $last_like['like_num'];
			if($like_num){
				$sql .= "SELECT mn.*,count(mn.id) as num ,sum(ml.like_num) as like_num FROM __MEMBER_NO__ as mn LEFT JOIN __MEMBER_NO_LIKE__ as ml ON mn.id=ml.member_no_id WHERE mn.id IS NOT NULL AND ml.create_time >={$month_time[0]} AND ml.create_time <={$month_time[1]} GROUP BY mn.id HAVING (like_num > {$like_num} OR (like_num = {$like_num} AND mn.like_time < {$info['like_time']})) ORDER BY like_num DESC,mn.like_time ASC,mn.id ASC";
				$rank_info = M()->query($sql);
				if(empty($rank_info)){
					$rank = 1;
				}else{
					$rank = count($rank_info)+1;
				}
			}else{
				$like_num = 0;
			}
		}
		$this->ajaxReturn(['s'=>true, 'm'=>'ok', 'info'=>['member_no'=>$info['member_no'], 'like_num'=>$like_num, 'rank'=>$rank]]);
	}

	/**
	 * 会员号点赞
	 * @Author   张亚伟<1743325520@qq.com>
	 * @DateTime 2018-10-12
	 * @return   
	 */
	public function member_no_like()
	{
		$member_no = I('member_no');
		$res = member_no_like($member_no, 1, $this->uid);
		if($res['status']){
			$this->ajaxReturn(['s'=>true, 'm'=>'点赞成功']);
		}else{
			$this->ajaxReturn(['s'=>false, 'm'=>$res['msg']]);
		}
		exit();

		$info = M('member_no')->where(['member_no'=>$member_no])->find();
		if(empty($info)){
			$this->ajaxReturn(['s'=>false, 'm'=>'会员号不存在']);
		}
		$likeModel = M('member_no_like');
		$has = $likeModel->where(['member_no_id'=>$info['id'], 'user_id'=>$this->uid])->order('id desc')->find();
		if(!empty($has)){
			if(date('Y-m-d', $has['create_time']) == date('Y-m-d')){
				$this->ajaxReturn(['s'=>false, 'm'=>'今天已点赞']);
			}
		}
		$res = $likeModel->add([
			'member_no_id'	=> $info['id'],
			'user_id'		=> $this->uid,
			'create_time'	=> time(),
		]);
		if($res){
			M('member_no')->where(['member_no'=>$member_no])->save(['like_time'=>time()]);
			$this->ajaxReturn(['s'=>true, 'm'=>'点赞成功']);
		}else{
			$this->ajaxReturn(['s'=>false, 'm'=>'点赞失败']);
		}
	}

	/**
	 * 绑定上级
	 * @return 
	 */
	public function bind_parent()
	{
		$member_no = I('member_no');
		if($this->user['first_leader']){
			$this->ajaxReturn(['s'=>false, 'm'=>'您已绑定过']);
		}
		if(empty($member_no)){
			$this->ajaxReturn(['s'=>false, 'm'=>'请输入会员号']);
		}
		$mn = M('member_no')->where(['member_no'=>$member_no])->find();
		if(empty($mn)){
			$this->ajaxReturn(['s'=>false, 'm'=>'会员号不存在']);	
		}
		$userModel = M('user');
		$parent_user = $userModel->where(['id'=>$mn['user_id']])->find();
		if(empty($parent_user)){
			$this->ajaxReturn(['s'=>false, 'm'=>'会员号不存在']);	
		}
		if($parent_user['id'] == $this->uid){
			$this->ajaxReturn(['s'=>false, 'm'=>'不能绑定自己的会员号']);	
		}
		$update = [
			'first_leader'	=> $parent_user['id'],
		];
		if($parent_user['first_leader']){
			$update['second_leader'] = $parent_user['first_leader'];		
		}
		$res = $userModel->where(['id'=>$this->uid])->save($update);
		if($res){
			$this->ajaxReturn(['s'=>true, 'm'=>'ok']);
		}else{
			$this->ajaxReturn(['s'=>false, 'm'=>'绑定失败']);
		}
	}

	/**
	 * 订单物流
	 * @return   [type]     [description]
	 */
	public function order_logistics()
	{
		$order_id = I('order_id');
		$order = M('order')->where(['id'=>$order_id, 'uid'=>$this->uid])->find();
		if(empty($order)){
			$this->ajaxReturn(['s'=>false, 'm'=>'订单不存在']);		
		}
		$postcom = logistics_com($order['logistics_type']);
		$logistics = ['status'=>0, 'msg'=>"失败"];
		if($postcom){
			$logistics_code = $order['logistics_code'];
			$res = queryExpress($postcom, $logistics_code);
			if($res){
				$logistics = $res;
			}
		}
		$this->ajaxReturn(['s'=>true, 'm'=>'ok', 'logistics'=>$user_list]);
	}

	/**
	 * 复购折扣
	 * @author 张亚伟<1743325520@qq.com>
	 * @return 
	 */
	public function product_discount()
	{
		$this->ajaxReturn(['s'=>true, 'm'=>'ok', 'discount'=>product_discount()]);
	}

	/**
	 * 检测商品是否已购买
	 * @author 张亚伟<1743325520@qq.com>
	 * @return
	 */
	public function check_product_buy()
	{
		$product_ids = I('product_ids');
		$is_buys = [];
		if($product_ids){
			$product_ids = explode(',', $product_ids);
			foreach ($product_ids as $key => $product_id) {
				if($product_id){
					$is_buy = product_is_buy($this->uid, $product_id);
					$is_buys[$product_id] = $is_buy ? 1:0;
				}
			}
		}
		$this->ajaxReturn(['s'=>true, 'm'=>'ok', 'is_buys'=>$is_buys]);
	}

	/**
	 * 提现配置
	 * @return
	 */
	public function withdrawals_config()
	{
		$min_amount = yzl_config('withdrawals.withdrawals_min_amount');
		$max_amount = yzl_config('withdrawals.withdrawals_max_amount');
		$bank_codes = withdrawals_bank_codes();
		$tax_rate = yzl_config('withdrawals.withdrawals_tax_rate');
		$rule = yzl_config('withdrawals.withdrawals_rule');
		$config = [
			'min_amount'	=> $min_amount,
			'max_amount'	=> $max_amount,
			'bank_codes'	=> $bank_codes,
			'tax_rate'		=> $tax_rate,
			'rule'			=> $rule,
		];
		$this->ajaxReturn(['s'=>true, 'm'=>'ok', 'config'=>$config]);
	}

	/**
	 * 提醒申请
	 * @author 张亚伟<1743325520@qq.com>
	 */
	public function withdrawals()
	{
		$bank_code = I('bank_code', '', 'trim');
		$bank_no = I('bank_no', '', 'trim');
		$bank_card_branch= I('bank_card_branch', '', 'trim');
		$user_name = I('user_name');
		$code = I('code');
		$mobile = I('mobile');
		$money = I('money');
		$source = I('source');
		$source_id = I('source_id');

		if(empty($bank_code)){
			$this->ajaxReturn(['s'=>false, 'm'=>'请选择银行卡类型']);
		}
		$bank_codes = withdrawals_bank_codes();
		if(!array_key_exists($bank_code, $bank_codes)){
			$this->ajaxReturn(['s'=>false, 'm'=>'银行卡类型暂不支持']);
		}
		$bank_name = $bank_codes[$bank_code];
		if(empty($bank_no)){
			$this->ajaxReturn(['s'=>false, 'm'=>'请输入银行卡号']);
		}
		if(in_array($source, [1, 2])){
			if(empty($money)){
				$this->ajaxReturn(['s'=>false, 'm'=>'请输入提现金额']);
			}
			$min_withdrawal_amount = yzl_config('withdrawals.withdrawals_min_amount');
			$max_withdrawal_amount = yzl_config('withdrawals.withdrawals_max_amount');
			if($money < $min_withdrawal_amount){
				$this->ajaxReturn(['s'=>false, 'm'=>'最低提现金额'.$min_withdrawal_amount]);
			}
			if($money > $max_withdrawal_amount){
				$this->ajaxReturn(['s'=>false, 'm'=>'最高提现金额'.$min_withdrawal_amount]);
			}
			if($this->user['phone']!=$mobile){
				$this->ajaxReturn(['s'=>false, 'm'=>'手机号错误', 'd'=>[$this->user, $mobile]]);
			}
		}
		if(empty($code)){
			$this->ajaxReturn(['s'=>false, 'm'=>'请输入验证码']);	
		}
		$varifyInfo = M('varify')->where(['phone'=>$mobile])->find();
		if (time() > $varifyInfo['ctime'] + 1800) {
			$this->ajaxReturn(['s'=>false, 'm'=>'验证码失效']);
		}
		if ($code != $varifyInfo['code']) {
			$this->ajaxReturn(['s'=>false, 'm'=>'验证码错误']);
		}
		switch ($source) {
			case '1':// 分销提现
				if($this->user['user_money'] < $money){
					$this->ajaxReturn(['s'=>false, 'm'=>'余额不足']);	
				}
				$tax_rate = yzl_config('withdrawals.withdrawals_tax_rate');
				// 税收扣除金额
				$tax_money = round($money*$tax_rate/100, 2);
				break;
			case '2':// 推广下线等级提现
				$tax_money = 0;
				$level_info = M('award_level')->where(['id'=>$source_id])->find();
				if(empty($level_info)){
					$this->ajaxReturn(['s'=>false, 'm'=>'等级奖励不存在，无法提现']);
				}
				if($money!=$level_info['award_money']){
					$this->ajaxReturn(['s'=>false, 'm'=>'等级奖励金额不对，请重新进入提现']);
				}
				break;
			case '3':// 抵用券
				$tax_money = 0;
				$vouchers = M('vouchers')->where(['code'=>$source_id])->find();
				if(empty($vouchers)){
					$this->ajaxReturn(['s'=>false, 'm'=>'抵用券不存在']);
				}
				if($vouchers['status'] != 2){
					$this->ajaxReturn(['s'=>false, 'm'=>'抵用券已被使用或失效']);
				}
				$money = $vouchers['money'];
				break;
			default:
				break;
		}
		$amount = $money-$tax_money;

		$data = [
			'user_id'	=> $this->uid,
			'source'	=> $source,
			'source_id'	=> $source_id,
			'bank_code'	=> $bank_code,
			'bank_name'	=> $bank_name,
			'bank_no'	=> $bank_no,
			'bank_card_branch'	=> $bank_card_branch,
			'user_name'	=> $user_name,
			'money'		=> $money,
			'amount'	=> $amount,
			'tax_money'	=> $tax_money,
			'create_time'=> time(),
			'update_time'=> time(),
		];
		$model = M('withdrawals');
		$model->startTrans();
		$withdrawal_id = $model->add($data);
		if($withdrawal_id){
			switch ($source) {
				case 1:
					$res = money_log($this->uid, -$money, 2, $withdrawal_id);
					if(!$res['status']){
						$model->rollback();
						$this->ajaxReturn(['s'=>false, 'm'=>$res['msg']]);
					}
					break;
				case 2:
					M('user_level_withdrawal')->add([
						'user_id'		=> $this->uid,
						'level'			=> $source_id,
						'money'			=> $money,
						'create_time'	=> time(),
					]);
					break;
				case 3:
					M('vouchers')->where(['code'=>$source_id])->save(['status'=>3]);
					break;
				default:
					break;
			}
			$model->commit();
			$this->ajaxReturn(['s'=>true, 'm'=>'提交成功', 'data'=>['total_amount'=>$money, 'amount'=>$amount, 'tax_money'=>$tax_money]]);
		}else{
			$model->rollback();
			$this->ajaxReturn(['s'=>false, 'm'=>'提交失败']);
		}
	}

	/**
	 * 提现记录
	 */
	public function withdrawals_list()
	{
		$page = I('page');
		$size = I('size');

		$list = M('withdrawals')->where(['user_id'=>$this->uid])->page($page, $size)->field('id,money,status,create_time as date')->select();
		if($list){
			$status_arr = ['1'=>'正在审核', '2'=> '申请成功', '3'=>'申请失败'];
			foreach ($list as $key => &$row) {
				$row['status_name'] = isset($status_arr[$row['status']]) ? $status_arr[$row['status']] : '';
				$row['date'] = date('Y-m-d H:i:s', $row['date']);
			}
		}
		$this->ajaxReturn(['s'=>true, 'm'=>'ok', 'list'=>$list]);
	}

	/**
	 * 首页图片
	 */
	public function home_img()
	{
		$imgs = [];
		$imgs[1] = yzl_config('home_img.home_img_1');
		$imgs[2] = yzl_config('home_img.home_img_2');
		$imgs[3] = yzl_config('home_img.home_img_3');
		$imgs[4] = yzl_config('home_img.home_img_4');
		$imgs[5] = yzl_config('home_img.home_img_5');
		$this->ajaxReturn(['s'=>true, 'm'=>'ok', 'imgs'=>$imgs]);
	}

    /**
     * 下载娱管家号
     */
    public function download_no()
    {
        $token = I('user_token');
        $user = M('user')->where(['cid'=>$token])->find();
        if(empty($user)){
            $user = M('token')->where(['token'=>$token])->find();
            if($user){
                $user['id'] = $user['uid'];
            }
        }
        if($user){
            $member_no_info = M('member_no')->where(['user_id'=>$user['id']])->find();
        }
        if(!empty($member_no_info)){
            $member_no = $member_no_info['member_no'];
        }else{
            $member_no = yzl_config('distribution.distribution_member_no');
        }
        $this->ajaxReturn(['s'=>true, 'm'=>'ok', 'member_no'=>$member_no]);
    }

    public function icon()
    {
    	$icons = [
    		'home_icon_1' 			=> yzl_config('icon.home_top_icon_1'),
    		'gr_content_icon_cjzx' 	=> yzl_config('icon.gr_content_icon_cjzx'),
    		'gr_content_icon_hdsq'	=> yzl_config('icon.gr_content_icon_hdsq'),
    	];
        $this->ajaxReturn(['s'=>true, 'm'=>'ok', 'icons'=>$icons]);
    }

    public function home_icon()
    {
    	$icons = [
    		[
    			'icon'	=> yzl_config('icon.home_top_icon_1'),
    			'text'	=> yzl_config('icon.home_top_text_1'),
    		],
    		[
    			'icon'	=> yzl_config('icon.home_top_icon_2'),
    			'text'	=> yzl_config('icon.home_top_text_2'),
    		],
    		[
    			'icon'	=> yzl_config('icon.home_top_icon_3'),
    			'text'	=> yzl_config('icon.home_top_text_3'),
    		],
    		[
    			'icon'	=> yzl_config('icon.home_top_icon_4'),
    			'text'	=> yzl_config('icon.home_top_text_4'),
    		],
    	];
        $this->ajaxReturn(['s'=>true, 'm'=>'ok', 'icons'=>$icons]);
    }

    public function login_code()
    {
        $this->ajaxReturn(['s'=>false, 'm'=>'']);
        $this->ajaxReturn(['s'=>true, 'm'=>'', 'code'=>'<p class="left-color"></p><p class="iconfont icon-weixin oauth" oauth="weixin"></p><p class="iconfont icon-qq oauth" oauth="qq"></p><p class="left-color right-color"></p>']);
    }

	/**
	 * 未读消息数量
	 * @return [type]
	 */
	public function unread_num()
	{
		$msg_num =  M('msg')->where(['to'=>$this->user['phone'], 'read_status'=>0])->count();
		$shop_num = 0;
		$shops = M('shop')->where([['uid'=>$uid], ['phone'=>$this->user['phone']], ['tel'=>$this->user['phone']], '_logic'=>'OR'])->select();
		if ($shops) {
			$shopids = array_column($shops, 'id');
			$shop_num = M('appointment')->where(array('type' => 1, 'shopid' => ['in', $shopids], 'is_read'=>0))->count();
		}
		$msg_num = intval($msg_num);
		$shop_num = intval($shop_num);
		$num = $msg_num + $shop_num;
		$this->ajaxReturn(array('s'=>true,'d'=>'ok', 'num'=>$num, 'msg_num'=>$msg_num, 'shop_num'=>$shop_num));
	}

	public function point_address()
	{
		$coordtype = I('coordtype');
		$lat = I('lat');
		$lng = I('lng');
		if(empty($lat) || empty($lng)){
			$this->ajaxReturn(array('s'=>false, 'm'=>'参数错误'));
		}
		$url = "http://api.map.baidu.com/reverse_geocoding/v3/?ak=gtLD7LMN8NTjihIG40m4INGrg9IHSlup&output=json&coordtype={$coordtype}&location={$lat},{$lng}";
		$res = file_get_contents($url);
		if($res && $res = json_decode($res, true)){
			if($res['status'] == 0){
				$this->ajaxReturn(array('s'=>true, 'm'=>'ok', 'r'=>$res['result']));
			}
		}
		$this->ajaxReturn(array('s'=>false, 'm'=>'获取失败'));
	}

	public function geocoding()
	{
		$city = I('city');
		$addr = I('addr');
		if(empty($addr)){
			$this->ajaxReturn(array('s'=>false, 'm'=>'参数错误'));
		}
		$url = "http://api.map.baidu.com/geocoding/v3/?ak=gtLD7LMN8NTjihIG40m4INGrg9IHSlup&output=json&city={$city}&address={$addr}";
		$res = file_get_contents($url);
		if($res && $res = json_decode($res, true)){
			if($res['status'] == 0){
				$this->ajaxReturn(array('s'=>true, 'm'=>'ok', 'r'=>$res['result']));
			}
		}
		$this->ajaxReturn(array('s'=>false, 'm'=>'获取失败'));
	}
}
?>
